标签:cout namespace gets jpg date == using 比较 col
#include<iostream> #include<vector> using namespace std; class Subject; class Obeserver{//观察者 public: Obeserver(){}; virtual ~Obeserver(){}; virtual void update(Subject * sub) = 0; }; class Subject{//被观察者 public: Subject(){}; virtual ~Subject(){}; Obeserver *m_Obeserver; void attach(Obeserver * pObeserver){ m_vtObj.push_back(pObeserver); } void detach(Obeserver * pObeserver){ for(auto itr = m_vtObj.begin();itr != m_vtObj.end(); ++itr){ if(*itr == pObeserver){ m_vtObj.erase(itr); return; } } } void notify(){ for(auto itr = m_vtObj.begin();itr != m_vtObj.end(); ++itr){ (*itr)->update(this); } } virtual int getState() = 0; virtual void setState(int i) = 0; private: vector<Obeserver*> m_vtObj; }; class ConcreteObeserver : public Obeserver{//具体的观察者 public: ConcreteObeserver(string name){m_objName = name;} ~ConcreteObeserver(){} void update(Subject * sub){ m_observerState = sub->getState(); cout << "update oberserver["<< m_objName << "] state:" << m_observerState << endl; } private: string m_objName; int m_observerState; }; class ConcreteSubject :public Subject{//具体的被观察者 public: int getState(){return state;} void setState(int i){state = i;} private: int state = 0; }; int main(int argc, char *argv[]) { Subject * subject = new ConcreteSubject(); Obeserver * objA = new ConcreteObeserver("A"); Obeserver * objB = new ConcreteObeserver("B"); subject->attach(objA); subject->attach(objB); subject->setState(1); subject->notify(); cout << "---------------------------------------------" << endl; subject->detach(objB); subject->setState(2); subject->notify(); return 0; }
类图:
观察者模式在注册回调这种应用中比较常用,很有用的一种设计模式了。
设计模式之- 观察者模式(Observer Pattern)
标签:cout namespace gets jpg date == using 比较 col
原文地址:https://www.cnblogs.com/J1ac/p/9695144.html