#ifndef SUBJECT_H
#define SUBJECT_H
#include<list>
#include "observer.h"
using namespace std;
class Observer;
class Blog
{
private:
list<Observer *> m_observers; //观察者列表
protected:
string m_status; //状态
public:
Blog() {}
virtual ~Blog() {}
void Attach(Observer *observer);   //添加观察者
void Remove(Observer *observer);    //移除观察者
void Notify();  //通知观察者
virtual void SetStatus(string s);   //设置状态
virtual string GetStatus(); //获得状态
};
class BlogCSDN : public Blog
{
private:
string m_name; //博主名字
public:
BlogCSDN(string name) : m_name(name) {}
~BlogCSDN() {}
void SetStatus(string s);
string GetStatus();
};
#endif
subject.cpp
#include "subject.h"
void Blog::Attach(Observer *observer)
{
m_observers.push_back(observer);
}
void Blog::Remove(Observer *observer)
{
m_observers.remove(observer);
}
void Blog::Notify()
{
list<Observer *>::iterator iter = m_observers.begin();
for(; iter != m_observers.end(); iter++) {
(*iter)->Update();
}
}
void Blog::SetStatus(string s)
{
m_status = s;
}
string Blog::GetStatus()
{
return m_status;
}
void BlogCSDN::SetStatus(string s)
{
m_status = "csdn通知: " +m_name + s;
}
string BlogCSDN::GetStatus()
{
return m_status;
}
main.cpp
#include "observer.h"
#include "subject.h"
int main()
{
Blog *blog = new BlogCSDN("zy416548283");
Observer *observer = new ObserverBlog("tutupig", blog);
blog->Attach(observer);
blog->SetStatus("发表观察者模式实现的文章");
blog->Notify();
delete blog;
delete observer;
return 0;
}
  编译运行:
  zy@zyPc:~/code/Cplus/designPattern/observer$ ./a.out
  tutupig-------csdn通知: zy416548283发表***文章