11bc80516SShuo Chen#include <algorithm> 21bc80516SShuo Chen#include <vector> 31bc80516SShuo Chen#include <stdio.h> 41bc80516SShuo Chen 51bc80516SShuo Chenclass Observable; 61bc80516SShuo Chen 71bc80516SShuo Chenclass Observer 81bc80516SShuo Chen{ 91bc80516SShuo Chen public: 101bc80516SShuo Chen virtual ~Observer(); 111bc80516SShuo Chen virtual void update() = 0; 121bc80516SShuo Chen 131bc80516SShuo Chen void observe(Observable* s); 141bc80516SShuo Chen 151bc80516SShuo Chen protected: 161bc80516SShuo Chen Observable* subject_; 171bc80516SShuo Chen}; 181bc80516SShuo Chen 191bc80516SShuo Chenclass Observable 201bc80516SShuo Chen{ 211bc80516SShuo Chen public: 221bc80516SShuo Chen void register_(Observer* x); 231bc80516SShuo Chen void unregister(Observer* x); 241bc80516SShuo Chen 251bc80516SShuo Chen void notifyObservers() 261bc80516SShuo Chen { 271bc80516SShuo Chen for (size_t i = 0; i < observers_.size(); ++i) 281bc80516SShuo Chen { 291bc80516SShuo Chen Observer* x = observers_[i]; 301bc80516SShuo Chen if (x) { 311bc80516SShuo Chen x->update(); // (3) 321bc80516SShuo Chen } 331bc80516SShuo Chen } 341bc80516SShuo Chen } 351bc80516SShuo Chen 361bc80516SShuo Chen private: 371bc80516SShuo Chen std::vector<Observer*> observers_; 381bc80516SShuo Chen}; 391bc80516SShuo Chen 401bc80516SShuo ChenObserver::~Observer() 411bc80516SShuo Chen{ 421bc80516SShuo Chen subject_->unregister(this); 431bc80516SShuo Chen} 441bc80516SShuo Chen 451bc80516SShuo Chenvoid Observer::observe(Observable* s) 461bc80516SShuo Chen{ 471bc80516SShuo Chen s->register_(this); 481bc80516SShuo Chen subject_ = s; 491bc80516SShuo Chen} 501bc80516SShuo Chen 511bc80516SShuo Chenvoid Observable::register_(Observer* x) 521bc80516SShuo Chen{ 531bc80516SShuo Chen observers_.push_back(x); 541bc80516SShuo Chen} 551bc80516SShuo Chen 561bc80516SShuo Chenvoid Observable::unregister(Observer* x) 571bc80516SShuo Chen{ 581bc80516SShuo Chen std::vector<Observer*>::iterator it = std::find(observers_.begin(), observers_.end(), x); 591bc80516SShuo Chen if (it != observers_.end()) 601bc80516SShuo Chen { 611bc80516SShuo Chen std::swap(*it, observers_.back()); 621bc80516SShuo Chen observers_.pop_back(); 631bc80516SShuo Chen } 641bc80516SShuo Chen} 651bc80516SShuo Chen 661bc80516SShuo Chen// --------------------- 671bc80516SShuo Chen 681bc80516SShuo Chenclass Foo : public Observer 691bc80516SShuo Chen{ 701bc80516SShuo Chen virtual void update() 711bc80516SShuo Chen { 721bc80516SShuo Chen printf("Foo::update() %p\n", this); 731bc80516SShuo Chen } 741bc80516SShuo Chen}; 751bc80516SShuo Chen 761bc80516SShuo Chenint main() 771bc80516SShuo Chen{ 781bc80516SShuo Chen Foo* p = new Foo; 791bc80516SShuo Chen Observable subject; 801bc80516SShuo Chen p->observe(&subject); 811bc80516SShuo Chen subject.notifyObservers(); 821bc80516SShuo Chen delete p; 831bc80516SShuo Chen subject.notifyObservers(); 841bc80516SShuo Chen} 85