未名
5毛党党员
全部博文(17)
2011年(1)
2009年(16)
anank
7717060
flw
HonestQi
scutan
cugb_cat
浅尝寂寞
gong_yue
分类: C/C++
2009-02-24 19:32:23
#include <string> #include <iostream> #include <list> using namespace std; using std::list; class Observer { public: virtual void Update() = 0; }; class Subject { private: list<Observer*> m_list_observer; public: virtual void Attach(Observer* observer) { m_list_observer.push_back(observer); } virtual void Detach(Observer* observer) { m_list_observer.remove(observer); } virtual void Notify() { list<Observer*>::iterator list_it; for(list_it = m_list_observer.begin();list_it != m_list_observer.end();list_it++) { (*list_it)->Update(); } } }; class ConcreateSubject :public Subject { private: string m_str_SubjectState; public: virtual string GetSubjectState(void) { return m_str_SubjectState; } virtual void SetSubjectState(string SubjectState) { m_str_SubjectState = SubjectState; } }; class ConcreateObserver : public Observer { private: string m_str_name; string m_str_SubjectState; ConcreateSubject* m_Subject; public: ConcreateObserver(ConcreateSubject* subject , string name) { m_Subject = subject; m_str_name = name; } void Update() { m_str_SubjectState = m_Subject->GetSubjectState(); cout<<"观察者"<<m_str_name<<"的新状态是"<<m_str_SubjectState<<endl; } ConcreateSubject* GetSubject(void) { return m_Subject; } void SetSubject(ConcreateSubject* subject) { m_Subject = subject; } }; int main(void) { ConcreateSubject* s = new ConcreateSubject(); ConcreateObserver* ob1 = new ConcreateObserver(s , "x"); s->Attach(ob1); s->Attach(new ConcreateObserver(s , "y")); s->Attach(new ConcreateObserver(s , "z")); s->SetSubjectState("ABC"); s->Notify(); cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl; s->Detach(ob1); s->SetSubjectState("DEF"); s->Notify(); };
上一篇:程序员的十层楼 11层(上帝)
下一篇:Perl语言入门习题_第四章
登录 注册