Advertisement
homer512

private observer

Jul 3rd, 2014
493
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.49 KB | None | 0 0
  1. /**
  2.  * Classic observer pattern
  3.  */
  4. class Observer
  5. {
  6. public:
  7.   virtual ~Observer() {}
  8.   virtual void notify() = 0;
  9. };
  10.  
  11. /**
  12.  * Subject of an Observer
  13.  */
  14. class Worker
  15. {
  16.   /**
  17.    * For simplicity, just a single Observer
  18.    */
  19.   Observer* on_finish;
  20. public:
  21.   void register_finish_observer(Observer* callback)
  22.   {
  23.     on_finish = callback;
  24.   }
  25.   void start()
  26.   {
  27.     // do something
  28.     on_finish->notify();
  29.   }
  30. };
  31.  
  32. /**
  33.  * Some class which is implemented as an Observer but being an Observer is
  34.  * just an implementation detail, not part of the API.
  35.  * Having public Observer methods would be wrong and clutter the interface.
  36.  * Therefore we use private inheritance
  37.  */
  38. class Dispatcher: private Observer
  39. {
  40.   Worker worker;
  41.   bool finished;
  42.  
  43.   /**
  44.    * Implements Observer::notify
  45.    *
  46.    * A private virtual function. Fancy that!
  47.    */
  48.   virtual void notify()
  49.   {
  50.     finished = true;
  51.   }
  52. public:
  53.   void start_work()
  54.   {
  55.     finished = false;
  56.     /* here we cast this object to Observer. Something we can only do in
  57.      * methods of this class
  58.      */
  59.     worker.register_finish_observer(this);
  60.     worker.start();
  61.   }
  62.   /**
  63.    * Normally, in private inheritance we can avoid using a virtual destructor
  64.    * as no external code can use our private interface and try to delete
  65.    * us through it. However, since we let the interface "escape" in the
  66.    * start_work method, we have to use a virtual destructor after all.
  67.    */
  68.   virtual ~Dispatcher() {}
  69. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement