#include #include #include #include "../Mutex.h" #include #include #include class Observable; class Observer : public boost::enable_shared_from_this { public: virtual ~Observer(); virtual void update() = 0; void observe(Observable* s); protected: Observable* subject_; }; class Observable { public: void register_(boost::weak_ptr x); // void unregister(boost::weak_ptr x); void notifyObservers() { muduo::MutexLockGuard lock(mutex_); Iterator it = observers_.begin(); while (it != observers_.end()) { boost::shared_ptr obj(it->lock()); if (obj) { obj->update(); ++it; } else { printf("notifyObservers() erase\n"); it = observers_.erase(it); } } } private: mutable muduo::MutexLock mutex_; std::vector > observers_; typedef std::vector >::iterator Iterator; }; Observer::~Observer() { // subject_->unregister(this); } void Observer::observe(Observable* s) { s->register_(shared_from_this()); subject_ = s; } void Observable::register_(boost::weak_ptr x) { observers_.push_back(x); } //void Observable::unregister(boost::weak_ptr x) //{ // Iterator it = std::find(observers_.begin(), observers_.end(), x); // observers_.erase(it); //} // --------------------- class Foo : public Observer { virtual void update() { printf("Foo::update() %p\n", this); } }; int main() { Observable subject; { boost::shared_ptr p(new Foo); p->observe(&subject); subject.notifyObservers(); } subject.notifyObservers(); }