目标:定义一种一对多的关系,让多个观察对象(公司员工)同时监听一个主题对象(秘书),主题对象状态发生变化时,会通知所有观察者,使它们能够更新自己。
示例一:
#include
#include
#include
using namespace std;
class Secretary;
//看股票的同事类(观察对象,观察者)
class StockObserver
{
private:
string name;
Secretary* sub;
public:
StockObserver(string strname,Secretary* strsub)
{
name = strname;
sub = strsub;
}
void Update();
};
//秘书类(主题对象,通知者)
class Secretary
{
private:
vector observers;
public:
string action;
void Add(StockObserver ob)
{
observers.push_back(ob);
}
void Notify()
{
vector::iterator p = observers.begin();
while(p != observers.end())
{
(*p).Update();
p++;
}
}
};
void StockObserver::Update()
{
cout << name << ":" << sub->action << ",不要玩股票了,要开始工作了" << endl;
}
//客户端
int main()
{
Secretary* p = new Secretary(); //创建统治者
//观察者
StockObserver* s1 = new StockObserver("小李",p);
StockObserver* s2 = new StockObserver("小赵",p);
//加入通知队列
p->Add(*s1);
p->Add(*s2);
//事件
p->action = "老板来了";
//通知
p->Notify();
return 0;
}
示例二:
#include
#include
#include
using namespace std;
class SecretaryBase;
//抽象观察者
class CObserverBase
{
protected:
string name;
SecretaryBase* sub;
public:
CObserverBase(string strname,SecretaryBase* strsub)
{
name = strname;
sub = strsub;
}
virtual void Update()=0;
};
//具体的观察者,看股票的
class StockObserver : public CObserverBase
{
public:
StockObserver(string strname,SecretaryBase* strsub)
: CObserverBase(strname,strsub)
{
}
virtual void Update();
};
//具体观察者,看NBA的
class NBAObserver : public CObserverBase
{
public:
NBAObserver(string strname,SecretaryBase* strsub)
: CObserverBase(strname,strsub)
{
}
virtual void Update();
};
//抽象通知者
class SecretaryBase
{
public:
string action;
vector observers;
public:
virtual void Attach(CObserverBase* ob) = 0;
virtual void Notify() = 0;
};
//具体通知者
class Secretary : public SecretaryBase
{
public:
void Attach(CObserverBase* ob)
{
observers.push_back(ob);
}
void Notify()
{
vector::iterator p = observers.begin();
while(p != observers.end())
{
(*p)->Update();
p++;
}
}
};
void StockObserver::Update()
{
cout << name << ":" << sub->action << ",不要玩股票了,要开始工作了" << endl;
}
void NBAObserver::Update()
{
cout << name << ":" << sub->action << ",不要看NBA了,老板来了" << endl;
}
//客户端
int main()
{
SecretaryBase* p = new Secretary(); //创建观察者
//被观察的对象
CObserverBase* s1 = new NBAObserver("小李",p);
CObserverBase* s2 = new StockObserver("小赵",p);
//加入观察队列
p->Attach(s1);
p->Attach(s2);
//事件
p->action = "老板来了";
//通知
p->Notify();
return 0;
}
阅读(584) | 评论(0) | 转发(0) |