基于MAP线程安全的观察者监听者模式
1 #include<map> 2 #include<string> 3 #include<vector> 4 #include<iostream> 5 #include<memory> 6 using namespace std; 7 8 class Listener 9 { 10 public: 11 Listener(string name):_name(name){} 12 virtual void handleMessage(int msgid) = 0; 13 string _name; 14 }; 15 16 class Listener1 : public Listener 17 { 18 public: 19 Listener1(string name):Listener(name){} 20 void handleMessage(int msgid) 21 { 22 cout<<_name<<" "; 23 switch(msgid) 24 { 25 case 0: 26 cout<<"handle 0 msg!"<<endl; 27 break; 28 case 1: 29 cout<<"handle 1 msg!"<<endl; 30 break; 31 default: 32 cout<<"recv invalid msg!"<<endl; 33 break; 34 } 35 } 36 }; 37 38 class Listener2 : public Listener 39 { 40 public: 41 Listener2(string name):Listener(name){} 42 void handleMessage(int msgid) 43 { 44 cout<<_name<<" "; 45 switch(msgid) 46 { 47 case 0: 48 cout<<"handle 0 msg!"<<endl; 49 break; 50 case 2: 51 cout<<"handle 2 msg!"<<endl; 52 break; 53 default: 54 cout<<"recv invalid msg!"<<endl; 55 break; 56 } 57 } 58 }; 59 60 class Listener3 : public Listener 61 { 62 public: 63 Listener3(string name):Listener(name){} 64 void handleMessage(int msgid) 65 { 66 cout<<_name<<" "; 67 switch(msgid) 68 { 69 case 1: 70 cout<<"handle 1 msg!"<<endl; 71 break; 72 case 3: 73 cout<<"handle 3 msg!"<<endl; 74 break; 75 default: 76 cout<<"recv invalid msg!"<<endl; 77 break; 78 } 79 } 80 }; 81 82 class Observer 83 { 84 public: 85 void registerMsg(weak_ptr<Listener> plistener,int msgid) 86 { 87 map<int,vector<weak_ptr<Listener>>>::iterator it = _obserMap.find(msgid); 88 if(it == _obserMap.end()) 89 { 90 vector<weak_ptr<Listener>> vec; 91 vec.push_back(plistener); 92 _obserMap.insert (make_pair(msgid,vec)); 93 } 94 else 95 { 96 it->second.push_back(plistener); 97 } 98 } 99 100 void dispatchMsg(int msgid) 101 { 102 map<int,vector<weak_ptr<Listener>>>::iterator it = _obserMap.find(msgid); 103 if(it!=_obserMap.end()) 104 { 105 vector<weak_ptr<Listener>>::iterator vit = it->second.begin(); 106 for(;vit!=it->second.end();++vit) 107 { 108 //(*vit)->handleMessage(msgid); 109 shared_ptr<Listener> p = (*vit).lock();//提升 110 if(p != NULL) 111 { 112 p->handleMessage(msgid); 113 } 114 } 115 } 116 } 117 private: 118 map<int,vector<weak_ptr<Listener>>> _obserMap; 119 }; 120 121 Observer obser; 122 int main() 123 { 124 //监听者线程 125 shared_ptr<Listener> p1(new Listener1("Listener1")); 126 shared_ptr<Listener> p2(new Listener2("Listener2")); 127 shared_ptr<Listener> p3(new Listener3("Listener3")); 128 129 //Observer obser; 130 131 obser.registerMsg(p1,0); 132 obser.registerMsg(p1,1); 133 obser.registerMsg(p2,0); 134 obser.registerMsg(p2,2); 135 obser.registerMsg(p3,1); 136 obser.registerMsg(p3,3); 137 138 //观察者线程 139 int msgid = 0; 140 while(true) 141 { 142 cout<<"msgid :"; 143 cin>>msgid; 144 145 obser.dispatchMsg(msgid); 146 } 147 return 0; 148 }
原文地址:https://www.cnblogs.com/lulu1997/p/8492072.html
时间: 2024-10-18 22:54:34