观察者模式就是一组1:n的对象 当目标出现变化的时候自动通知到观察者: 代码如下: (估计有点问题) /* 02.23.2009 www.gaimo.net ccsdu2004@yahoo.com.cn */ #include <iostream> #include <list> #include <string> using namespace std; class Observer; class Subject { public: virtual void Attach(Observer *o) = 0; virtual void Nodify() = 0; //virtual void Detach() = 0; }; class Observer { public: virtual void Update(Subject *o) = 0; }; class Boy: public Subject { public: Boy() { o = new list<Observer*>(); } ~Boy(){delete o;} public: void SetName(string str){name.swap(str);} void Attach(Observer *ob) { this->o->push_back(ob); } void Nodify() { cout<<"please note."<<endl; list<Observer*>::iterator itr = o->begin(); while(itr != o->end()) { (*itr)->Update(this); itr ++; } } private: list<Observer*> *o; string name; }; class Girl: public Observer { public: void Update(Subject *sub) { cout<<"girl is update: "<<endl; //sub->Nodify(); } }; int main() { Boy *boy = new Boy(); boy->SetName("one boy"); Girl *girl1 = new Girl(); Girl *girl2 = new Girl(); Girl *girl3 = new Girl(); boy->Attach(girl1); boy->Attach(girl2); boy->Attach(girl3); boy->Nodify(); delete boy; delete girl1; delete girl2; delete girl3; system("PAUSE"); return 0; } 今天在公司的时候大致看的 估计有点问题 但是对这个模式的原理有了认识