观察者模式:属于行为型模式基本原理:当一个对象被修改时,会自动通知它的依赖对象。主要流程: 1.创建一个对象,存储它的所有依赖对象 2.在对象被修改的时候,通知所有依赖的对象 3.创建依赖对象,有统一的刷新方法 注意:避免循环依赖
#include <iostream> #include <string> #include <vector> using namespace std; //依赖对象基类 class Observer { public: virtual void update() = 0;//统一的刷新方法 }; //被依赖的对象 class Subject { private: vector<Observer*> observers;//用来存储所有依赖对象 int state; public: int getState() { return this->state; } void setState(int state) { this->state = state; notifyAllObservers();//对象改变的时候通知所有依赖对象 } void attach(Observer *observer)//用来存储依赖对象的方法 { observers.push_back(observer); } void notifyAllObservers()//通知依赖对象的方法 { for(int i=0; i<this->observers.size();++i) { this->observers[i]->update(); } } }; //依赖对象的实现 class BinaryObserver : public Observer { public: Subject *subject; BinaryObserver(Subject *subject) { this->subject = subject; this->subject->attach(this);//调用存储方法,将该依赖对象存起来 } void update() { cout<<"Binary String: "<<this->subject->getState()<<endl; } }; class OctalObserver : public Observer { public: Subject *subject; OctalObserver(Subject *subject) { this->subject = subject; this->subject->attach(this); } void update() { cout<<"Octal String: " <<this->subject->getState()<<endl; } }; class HexaObserver : public Observer { public: Subject *subject; HexaObserver(Subject *subject) { this->subject = subject; this->subject->attach(this); } void update() { cout<<"Hex String: " <<this->subject->getState()<<endl; } }; int main() { Subject *subject = new Subject(); new HexaObserver(subject); new OctalObserver(subject); new BinaryObserver(subject); cout<<"First state change: 15"<<endl; subject->setState(15); cout<<"Second state change: 10"<<endl; subject->setState(10); return 0; }