mardi 2 février 2016

C++ generic observer pattern

I'm working with code, which has a lot of observer pattern implementations. All of them are organized in such a manner:

Some interface to be implemented by observers:

class ObserverInterface {
  virtual void FooOccurs() = 0;
};

Some class, which implements Register, Unregister and notifications:

class ObservableImpl {
  public:
    Register(ObserverInterface *observer);
    Unregister(ObserverInterface *observer);

  private:
    void SomeMethod() {
      // foo things
      for(auto &observer: observers) {
        observer.FooOccurs();
      }
    }
};

Every time there is a copy-paste of Register and Unregister as well as implementation of notification for each method of ObserverInterface. And every time a programmer has to remember about calling Unregister(), if its observer is going to be destructed.

I wish to enclose the observer pattern in two class templates. So far I've got something like that: http://ift.tt/1JVCbDW

But I'm not sure if I'm not reinventing the wheel. Are there any easier, commonly known approach to do that?

Aucun commentaire:

Enregistrer un commentaire