#include <iostream> #include <string> #include <vector> #include <algorithm> #include <functional> using namespace std; class Observer { public: Observer(){} virtual ~Observer(){} virtual void run()=0; protected: string _name; }; class atlete : public Observer { public: atlete(string name){_name=name;} virtual ~atlete(){} void run() { cout<<"atlete "<<_name<<" run"<<endl; } }; class Subject { public: Subject(){} virtual void notify()=0; virtual void attach(Observer*)=0; virtual void detach(Observer*)=0; protected: vector<Observer*> vec; }; class referee : public Subject { public: referee(){} virtual ~referee(){} void attach(Observer* p) { vec.push_back(p); } void detach(Observer* p) { vec.erase(remove_if(vec.begin(),vec.end(),bind1st(equal_to<Observer*>(),p))); } void notify() { cout<<"referee say 'run'"<<endl; vector<Observer*>::iterator it; for (it=vec.begin();it!=vec.end();it++) { (*it)->run(); } } }; int main() { Observer *pat1=new atlete("zhangsan"); Observer *pat2=new atlete("lisi"); Observer *pat3=new atlete("wangwu"); Subject *pre=new referee; pre->attach(pat1); pre->attach(pat2); pre->attach(pat3); pre->notify(); cout<<endl; pre->detach(pat2); pre->notify(); delete pat1; delete pat2; delete pat3; delete pre; system("pause"); return 0; }