观察者模式

当某个类改变时,其他的多个类需要得到消息并执行自己的事情。  这种需求下可以使用观察者模式

 1 #include <iostream>
 2 #include <string>
 3 #include <vector>
 4 using namespace std;
 5 
 6 
 7 class  Observer{   // 观察者类
 8   public:
 9     std::string  context;
10   public:
11     void  ShowString()
12     {
13       std::cout << context << std::endl; 
14     }
15 };
16 
17 class   Server{  //改变类
18   private:
19     vector<Observer*> vec_obs;
20   public:
21     void  attach(Observer * obs);
22 
23     void Notify();
24 };
25 
26 void Server::attach(Observer *obs){
27 
28   vec_obs.push_back(obs);
29 }
30 
31 void Server::Notify(){
32 
33   for(vector<Observer*>::iterator it = vec_obs.begin();it != vec_obs.end();it++ )
34      (*it)->context = "Server update()";
35 
36 }
37 
38 
39 
40 int main()
41 {
42   Server s;
43   Observer o;
44   s.attach(&o);
45   
46   s.Notify();
47 
48   o.ShowString();
49 
50 
51   return 0;
52 }

十分有用的设计模式,当类之间存在这种依托关系时,可以使用。

原文地址:https://www.cnblogs.com/xuxu8511/p/3223458.html