homer512 icon

private observer

homer512 | PRO | 07/03/14 07:56:52 PM UTC | 0 ⭐ | 1029 👁️ | Never ⏰ | []
C++ |

1.49 KB

|

None

|

0 👍

/

0 👎

/**
 * Classic observer pattern
 */
class Observer
{
public:
  virtual ~Observer() {}
  virtual void notify() = 0;
};
 
/**
 * Subject of an Observer
 */
class Worker
{
  /**
   * For simplicity, just a single Observer
   */
  Observer* on_finish;
public:
  void register_finish_observer(Observer* callback)
  {
    on_finish = callback;
  }
  void start()
  {
    // do something
    on_finish->notify();
  }
};
 
/**
 * Some class which is implemented as an Observer but being an Observer is
 * just an implementation detail, not part of the API.
 * Having public Observer methods would be wrong and clutter the interface.
 * Therefore we use private inheritance
 */
class Dispatcher: private Observer
{
  Worker worker;
  bool finished;
 
  /**
   * Implements Observer::notify
   *
   * A private virtual function. Fancy that!
   */
  virtual void notify()
  {
    finished = true;
  }
public:
  void start_work()
  {
    finished = false;
    /* here we cast this object to Observer. Something we can only do in
     * methods of this class
     */
    worker.register_finish_observer(this);
    worker.start();
  }
  /**
   * Normally, in private inheritance we can avoid using a virtual destructor
   * as no external code can use our private interface and try to delete
   * us through it. However, since we let the interface "escape" in the
   * start_work method, we have to use a virtual destructor after all.
   */
  virtual ~Dispatcher() {}
};

Comments