chrise
chrise

Reputation: 4253

c++ what design will help avoid multiple inheritance when using listeners

I have larger project where many smaller classes listen to some data and in certain instances notify other classes. So i have classes like

class Calc {}

class Spotter {}

class Updater {}

....

and some other classes that listen to them

class Listener_1 {}

class Listener_2 {}

And the project ended up with many interfaces

class ICalcListener {
    virtual void onCalcCall( ... ) {}

class ISpotterListener {
    virtual void on SpotterCall( ... ) {}

....

And the listeners are not inheriting all the listeners and overwrite the callback where they need to react.

class Listener_1 : public ICalcListener, public ISpotterListener, ... {
    virtual void onCalcCall( ... ) { doThis(); }
}

The design is functioning, but I am wondering if there is a better way to deal with this than Interfacing and inheriting myself to the maximum here. Mostly all I need is to register a callback.

EDIT: I was poking round more and and it seems like the alternative to using interfaces is using ( I am using c11 ) 1.) delegate 2.) std::function 3.) lambda function

If performance matters, but simplicity is also appreciated, what is the best way to go?

Upvotes: 0

Views: 185

Answers (1)

Mr D
Mr D

Reputation: 106

Multiple inheritance from several abstract classes with methods only is not that bad, and it works. I agree it produces a lot of "junky" code to support all the types of notifications you have.

Basically, having IXXXNotify abstract class for every event is more Java style.

I don't know exactly what your project is and how it does things, but you could try looking for these alternatives:

  1. Stick to INotify abstract classes, but make it more generic, so they will have only one argument like Event which will carry on all required information including event type. This will reduce amount of interface classes but will introduce additional headache with switch statements on event types. This approach breaks "OOPness" of your code a bit.

  2. Make a generic event/message bus, where again you'll have generic Event parameters and objects which interested in particular events can subscribe to them. Take a look at visitor or observer pattern and think of them in more generic way.

  3. Use std::function as your "event handler". Drawback here is that you can only assign one handler to any given event. You can overcome this by adding a layer on top of std::function.

  4. Take a look at existing libraries which already handle this, like Qt or boost.

Upvotes: 1

Related Questions