/* 观察者模式:定义一种一对多的依赖,让多个观察者对象同时监听某一个主题对象,这个主题对象发生变化时, 会通知所有观察者对象,使得他们能够自动更新自己 */ #include <iostream> #include <vector> #include <string> #include <algorithm> using namespace std; class Observer { public: virtual void Update() {} }; class Subject { vector<Observer*> observers; public: virtual void Notify() { vector<Observer*>::iterator iter = observers.begin(); for(; iter != observers.end(); iter++) { (*iter)->Update(); } } void AddObserver(Observer *observer) { observers.push_back(observer); } void DeleteObserver(Observer *observer) { vector<Observer*>::iterator iter = observers.end(); while(iter != observers.end()) { if(*iter == observer) { observers.erase(iter); } } } }; class ConcreteSubject:public Subject { private: string subjectstate; public: ConcreteSubject(string state) { subjectstate = state; } string State() { return subjectstate; } }; class ConcreteObserver:public Observer { ConcreteSubject *subject; string name; public: ConcreteObserver(ConcreteSubject *subject,string name) { this->subject = subject; this->name = name; } void Update() { cout<<"Observer "<<name<<" observer subject state is "<< this->subject->State()<<endl; } }; int main() { ConcreteSubject *subject = new ConcreteSubject("unhappy"); ConcreteObserver *observer1 = new ConcreteObserver(subject, "observer1"); ConcreteObserver *observer2 = new ConcreteObserver(subject, "observer2"); ConcreteObserver *observer3 = new ConcreteObserver(subject, "observer3"); subject->AddObserver(observer1); subject->AddObserver(observer2); subject->AddObserver(observer3); subject->Notify(); delete subject; delete observer1; delete observer2; delete observer3; system("pause"); return 0; }
C++实现观察者模式
最新推荐文章于 2022-09-08 15:23:56 发布