OOP-重写构造函数中调用的init方法



我有一个由两个类组成的简单类层次结构。这两个类都调用特定于该类的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方法容易出错
  2. 使用这种设置,CCD_ 1将被调用两次

但从语义上讲,这对我来说是有意义的:我想通过加载更多的处理程序来扩展类A在类B中的行为,但仍然保持类A加载的处理程序。此外,这是一项必须在构造中完成的任务。那么,如何通过更稳健的设计来解决这一问题呢?

您可以这样做:

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 
        // ...
    }
}

您可以将其视为一种设计模式模板方法。

最新更新