Search code examples
c++signals-slotsobserver-pattern

C++ Observer pattern listener event methods/class or signals & slots


Hy, I am implementing MVC in my game and i can't get this thing to work in my head. I decoupled view from game logics and controller is decoupled to. Thing actually works, but i can't decide if Listener pattern or signals & slots is better for my case.

I have base class Entity with few pure virtual methods:

onEntityCreate //Called when new entity is allocated
onEntityDelete //Called when new entity is deallocated
onEntityBuild //Called on respawn or spawn
onEntityDispose //Called before respawn or deallocation
onEntityTick //called every tick when is entity "alive"
onEntityUpdate //called when entity position/orientation updates

i would like to run view and logics in two different threads. If i could dispatch these events at the end of logics tick to view but i don't know how.


Solution

  • In my experience you should go with some hybrid Signal/Slots inside an abstract class, mainly because the Listener pattern doesn't work very well on C++ as inner classes have zero visibility over the outer class (as in Java, per example), making the insertion of listeners a very daunting task. So, you could use the great Gallant Signals, witch is a very fast implementation of the Delegate/Signal pattern:

    class EntityProvider {
    public:
        Gallant::Signal0< Entity* > onEntityCreate;
    };
    

    and on the code you use the provider:

    void Example::bindProvider(EntityProvider* provider) {
      provider->onEntityCreate.Connect(this, &Example::onEntityCreate);
    }
    

    Also, to get a better OO design you should use a "gluer" class, that is responsible to bind/unbind classes to their providers. This is good to centralize the event management and avoid hard-to-debug problems.