1#include <algorithm>
2#include <vector>
3#include <stdio.h>
4
5class Observable;
6
7class Observer
8{
9 public:
10  virtual ~Observer();
11  virtual void update() = 0;
12
13  void observe(Observable* s);
14
15 protected:
16  Observable* subject_;
17};
18
19class Observable
20{
21 public:
22  void register_(Observer* x);
23  void unregister(Observer* x);
24
25  void notifyObservers()
26  {
27    for (size_t i = 0; i < observers_.size(); ++i)
28    {
29      Observer* x = observers_[i];
30      if (x) {
31        x->update(); // (3)
32      }
33    }
34  }
35
36 private:
37  std::vector<Observer*> observers_;
38};
39
40Observer::~Observer()
41{
42  subject_->unregister(this);
43}
44
45void Observer::observe(Observable* s)
46{
47  s->register_(this);
48  subject_ = s;
49}
50
51void Observable::register_(Observer* x)
52{
53  observers_.push_back(x);
54}
55
56void Observable::unregister(Observer* x)
57{
58  std::vector<Observer*>::iterator it = std::find(observers_.begin(), observers_.end(), x);
59  if (it != observers_.end())
60  {
61    std::swap(*it, observers_.back());
62    observers_.pop_back();
63  }
64}
65
66// ---------------------
67
68class Foo : public Observer
69{
70  virtual void update()
71  {
72    printf("Foo::update() %p\n", this);
73  }
74};
75
76int main()
77{
78  Foo* p = new Foo;
79  Observable subject;
80  p->observe(&subject);
81  subject.notifyObservers();
82  delete p;
83  subject.notifyObservers();
84}
85