观察者模式
代码来自他人博客:https://blog.csdn.net/mct_blog/article/details/34810183
1 #include<iostream> 2 #include<list> 3 #include<string> 4 using namespace std; 5 class Observer; 6 class Subject //主题 7 { 8 public: 9 virtual void notify()=0; 10 virtual void attach(Observer *o)=0; 11 virtual void detach(Observer *o)=0; 12 string getState() 13 { 14 return state; 15 } 16 void setState(string s) 17 { 18 state = s; 19 } 20 protected: 21 string state; 22 list<Observer*> l; 23 /* 24 我的理解: 25 关键是主题类中有观察者实例的指针; 26 通过指针调用观察者的函数(函数传参,发消息)。 27 注:子类指针赋值给基类,没有问题(不会丢失子类独有的方法等、没有语法问题)。 28 */ 29 }; 30 class Observer 31 { 32 public: 33 virtual void update(Subject *s) 34 { 35 cout << "Observer::update" << endl; 36 } 37 }; 38 class ConcreteSubject:public Subject 39 { 40 public: 41 virtual void notify() 42 { 43 list<Observer*>::iterator it = l.begin(); 44 while(it != l.end()) 45 { 46 (*it)->update(this); 47 it++; 48 } 49 } 50 virtual void attach(Observer *o) 51 { 52 l.push_back(o); 53 } 54 virtual void detach(Observer *o) 55 { 56 l.remove(o); 57 } 58 }; 59 class Observer1:public Observer 60 { 61 public: 62 virtual void update(Subject *s) 63 { 64 cout << "Observer1::update Subject's state is " << s->getState() << endl; 65 } 66 }; 67 class Observer2:public Observer 68 { 69 public: 70 virtual void update(Subject *s) 71 { 72 cout << "Observer2::update Subject's state is " << s->getState() << endl; 73 } 74 }; 75 76 int main() 77 { 78 Observer1 o1; 79 Observer2 o2; 80 ConcreteSubject cs; 81 cs.attach(&o1); 82 cs.attach(&o2); 83 cs.setState("state1"); 84 cs.notify(); 85 cs.setState("state2"); 86 cs.notify(); 87 return 0; 88 }