samedi 20 janvier 2018

Where to register EventHandlers (Observer Pattern)?

I'm writing the plugin for application that uses Observer Pattern, so I don't have control over the "Subject" class, but I can register to them.

And since I'm trying to implement it the right way, I'm trying to find the best moment to register my observers. Most of tutorials show only class structure and do everything from "main", but I'm looking for some real world usage examples.

If I should pass the &subjests (event dispatchers) as parameters in constructor of my observer class (Dependency Injection?) or should I keep them global and register them from some random function via g_subject->addObserver(g_myObserver)

How do you people do it in real apps?

Observer class:

class Observer
{
public:
  virtual ~Observer() {}
  virtual void onNotify(const Entity& entity, Event event) = 0;
};

Subject class:

class Subject
{
public:
  void addObserver(Observer* observer);
  void removeObserver(Observer* observer);

  // Other stuff...
};

Aucun commentaire:

Enregistrer un commentaire