OOP - 覆盖构造函数中调用的init方法

时间:2015-02-09 10:15:25

标签: oop constructor override

我有两个类的简单类层次结构。这两个类都调用特定于该类的init方法。因此,init-方法在子类中被覆盖:

class A
{
    public A() { this->InitHandlers(); }

    public virtual void InitHandlers() { // load some event handlers here }
}

class B: public A
{
    public B() { this->InitHandlers(); }

    public virtual void InitHandlers() {

        // keep base class functionality
        A::InitHandlers();

        // load some other event handlers here 
        // ...
    }
}

我知道这是邪恶的设计:

  1. 从构造函数调用overriden方法是error-prone
  2. 使用此设置将
  3. B::InitHandlers()调用两次。
  4. 但从语义上讲它对我来说很有意义:我希望通过加载更多处理程序来扩展类B中的类A的行为,但仍然保持处理程序由类A加载。此外,这是一项必须在构造中完成的任务。那么如何通过更强大的设计来解决这个问题呢?

1 个答案:

答案 0 :(得分:0)

您可以这样做:

class A
{
    protected boolean init = false;

    public A() { this->Init(); }

    public virtual void Init() {
        if (!this->init) {
            this->init = true;
            this->InitHandlers();
        }
    }

    public virtual void InitHandlers() {
        // load some event handlers here
    }
}

class B: public A
{
    public B() { this->Init(); }

    public virtual void InitHandlers() {
        // keep base class functionality
        A::InitHandlers();

        // load some other event handlers here 
        // ...
    }
}

您可以将其视为设计模式template method

相关问题