0

I have a simple class hierarchy of two classes. Both classes call an init-method specific to that class. Therefor the init-method is overriden in the subclass:

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

I know this is evil design:

  1. The call of an overriden method from constructor is error-prone.
  2. B::InitHandlers() would be called twice with this setup.

But semantically it makes sense to me: I want to extend the behaviour of class A in class B by loading more handlers but still keeping the handlers loaded by class A. Further this is a task that has to be done in construction. So how can this be solved with a more robust design?

Community
  • 1
  • 1
Michbeckable
  • 1,851
  • 1
  • 28
  • 41

1 Answers1

0

You can do something like this:

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

You can see it as a design pattern template method.

Gnucki
  • 5,043
  • 2
  • 29
  • 44