1#include <algorithm> 2#include <vector> 3#include <stdio.h> 4#include "../Mutex.h" 5#include <boost/enable_shared_from_this.hpp> 6#include <boost/shared_ptr.hpp> 7#include <boost/weak_ptr.hpp> 8 9class Observable; 10 11class Observer : public boost::enable_shared_from_this<Observer> 12{ 13 public: 14 virtual ~Observer(); 15 virtual void update() = 0; 16 17 void observe(Observable* s); 18 19 protected: 20 Observable* subject_; 21}; 22 23class Observable 24{ 25 public: 26 void register_(boost::weak_ptr<Observer> x); 27 // void unregister(boost::weak_ptr<Observer> x); 28 29 void notifyObservers() 30 { 31 muduo::MutexLockGuard lock(mutex_); 32 Iterator it = observers_.begin(); 33 while (it != observers_.end()) 34 { 35 boost::shared_ptr<Observer> obj(it->lock()); 36 if (obj) 37 { 38 obj->update(); 39 ++it; 40 } 41 else 42 { 43 printf("notifyObservers() erase\n"); 44 it = observers_.erase(it); 45 } 46 } 47 } 48 49 private: 50 mutable muduo::MutexLock mutex_; 51 std::vector<boost::weak_ptr<Observer> > observers_; 52 typedef std::vector<boost::weak_ptr<Observer> >::iterator Iterator; 53}; 54 55Observer::~Observer() 56{ 57 // subject_->unregister(this); 58} 59 60void Observer::observe(Observable* s) 61{ 62 s->register_(shared_from_this()); 63 subject_ = s; 64} 65 66void Observable::register_(boost::weak_ptr<Observer> x) 67{ 68 observers_.push_back(x); 69} 70 71//void Observable::unregister(boost::weak_ptr<Observer> x) 72//{ 73// Iterator it = std::find(observers_.begin(), observers_.end(), x); 74// observers_.erase(it); 75//} 76 77// --------------------- 78 79class Foo : public Observer 80{ 81 virtual void update() 82 { 83 printf("Foo::update() %p\n", this); 84 } 85}; 86 87int main() 88{ 89 Observable subject; 90 { 91 boost::shared_ptr<Foo> p(new Foo); 92 p->observe(&subject); 93 subject.notifyObservers(); 94 } 95 subject.notifyObservers(); 96} 97 98