jeudi 14 mars 2019

Multiple inheritance: calling all the overriden functions

I have several behaviors that I want a class to have. I'd like to isolate these behaviors, so that I can reuse that code, mix and match at will.

For example, a way to do this would be:

class BehaviorAbstract {
     virtual void processInfo(Info i) = 0;
}

class Behavior1: public BehaviorAbstract {
     virtual void processInfo(Info i) { ... }
     void performBehavior1()  { ... }
}

class Behavior2: public BehaviorAbstract {
     virtual void processInfo(Info i) { ... }
     void performBehavior2()  { ... }
}

class ConcreteObject: public Behavior1, Behavior2 {
     void processInfo(Info i) {
       // needs to call processInfo of Behavior1 and Behavior2
       Behavior1::processInfo(i);
       Behavior2::processInfo(i);
     }
     void perform() {
       this->performBehavior1(); this->performBehavior2();
     }
 }

So here's the crux of the matter: ConcreteObject needs to call the 2 functions processInfo (same name, same arguments) of all the classes it inherits from. Imagine that all the behavior classes are coded by different developers. The function HAS to have the same name, because they all derive from BehaviorAbstract.

What's a reasonable design pattern to do this? I suspect multiple inheritance might be wrong here, and maybe a "multiple composition" would be better, but I need all the Behavior classes and the ConcreteObject to derive from BehaviorAbstract and they all need to operate on the same protected data member of BehaviorAbstract.

The solution I wrote above feels wrong and ugly. Is there a way to call automatically all the parent classes that implement processInfo, without explicitely having to rewrite their name?

Thanks a lot for the help.

Aucun commentaire:

Enregistrer un commentaire