观察者模式,有时我们又称为发布模式,当一个基类的状态(如某个属性)改变后,将会通知所有继承它的类的状态进行改变。
#include <iostream> #include <list> #include <numeric> #include <algorithm> using namespace std; class ObserBase; //base class of earth class EarthBase { public: virtual void attach(ObserBase *o)=0; virtual void change()=0; virtual void setWeather(string str)=0; virtual string getWeather()=0; }; //base class of observer class ObserBase { public: virtual string getName()=0; virtual void update(EarthBase *s)=0; virtual void changeWeather(string weather)=0; }; //earth class class Earth:public EarthBase { private: string weather; std::list<ObserBase*> l; public: Earth() { }; void attach(ObserBase *o) { this->l.push_back(o); }; void change() { for(std::list<ObserBase*>::iterator it=l.begin();it!=l.end();++it) { (*it)->update(this); } }; void setWeather(string str) { this->weather=str; change(); }; string getWeather() { return this->weather; }; }; //oberver class, or satellite class Observer:public ObserBase { private: string name; EarthBase* sub; public: Observer(string str) { name=str; }; Observer(string str,EarthBase* sub_) { name=str; sub = sub_; sub->attach(this); }; string getName() { return name; }; void update(EarthBase *s) { cout<<this->getName()+ " " + s->getWeather()<<endl; }; void changeWeather(string weather) { sub->setWeather(weather); } }; int main(int argc, char *argv[]) { Earth e; Observer *s1 = new Observer("风云一号"); Observer *s2 = new Observer("风云二号"); Observer *s3 = new Observer("风云三号"); Observer *s4 = new Observer("风云四号"); Observer *s5 = new Observer("风云五号",&e); e.attach(s1); e.attach(s2); e.attach(s3); e.attach(s4); e.setWeather("fine"); s5->changeWeather("bad weather!!"); return 0; }