例2:
Test_Observer.cpp /* 千万要注意对象切割问题的出现。一定要理解。 */ #include <iostream> #include <string> #include <vector> using namespace std; class Observer { protected: string name; public: virtual void update() { cout<<"Observer"<<endl; } }; class Man:public Observer { public: Man(string name) { this->name=name; } void update() { cout<<name<<" Man is coming"<<endl; } }; class Woman:public Observer { public: Woman(string name) { this->name=name; } void update() { cout<<name<<" Woman is leaving"<<endl; } }; class Subject { private: vector<Observer*> obser; public: void add(Observer &ob) { obser.push_back(&ob); } void notify() { for (vector<Observer*>::iterator it=obser.begin(); it!=obser.end(); it++) { (*it)->update(); } } }; int main() { Subject secret; Man m1("m1--"); Man m2("m2--"); Woman w1("w1"); Woman w2("w2"); secret.add(m1); secret.add(m2); secret.add(w1); secret.add(w2); secret.notify(); return 0; } |