观察者模式原理:当有新的消息产生时发送给观察者,和中介者模式的不同地方是中介者模式强调中介的作用以及中介双方的交互,观察者模式是主动调用观察者成员函数进行消息发送。
代码如下:
#include <iostream> #include <string> #include <list> using namespace std; class Observer { public: virtual void Update() { } }; class Blog { public: void attach(Observer *pobserver) { m_listObserver.push_back(pobserver); } void remove(Observer *pobserver) { m_listObserver.remove(pobserver); } virtual void SetStatus(string s) { } virtual string GetStatus() { return m_status; } void Notify() { list<Observer*>::iterator iter = m_listObserver.begin(); for (;iter != m_listObserver.end();iter++) { (*iter)->Update(); } } private: list<Observer*> m_listObserver; protected: string m_status; }; class ObserverBlog:public Observer { public: ObserverBlog(string name,Blog *blog): m_name(name), m_blog(blog) {} virtual void Update() { string status = m_blog->GetStatus(); cout<<m_name<<"-------"<<status<<endl; } private: string m_name; Blog *m_blog; }; class BlogCSDN:public Blog { public: BlogCSDN(string name):m_name(name){} virtual void SetStatus(string s) { m_status = "CSDN通知:" + m_name + s ; Notify(); } virtual string GetStatus() { return m_status; } private: string m_name; }; int main() { Blog *pblog = new BlogCSDN("liuwei"); Observer *pobserver = new ObserverBlog("lin",pblog); pblog->attach(pobserver); pblog->SetStatus("发表了一篇新博客"); return 0; }