观察者模式——三英雄战吕布

Posted on 2011-12-23 11:30  一年级的小学生  阅读(381)  评论(0编辑  收藏  举报

观察者模式:

被观察者:吕布

观察者:张飞,关羽,刘备

 

#include <iostream>
#include <vector>
#include <list>
using namespace std;

class SubjectPeople;
class ObserverPeople
{
public:
virtual void Action()=0;
};

class SubjectPeople
{
public:
virtual void RegisterPeople(ObserverPeople* ob) = 0;
virtual void RemovePeople(ObserverPeople* ob) = 0;
virtual void NotifyPeople() = 0;
};

class LvBuSubject:public SubjectPeople
{
protected:
list<ObserverPeople *> OP;

public:
void RegisterPeople(ObserverPeople* ob)
{
OP.push_back(ob);
}

void RemovePeople(ObserverPeople* ob)
{
list<ObserverPeople*>::iterator it = OP.begin();
while (it!=OP.end())
{
if (*it==ob)
{
OP.remove(*it);
return ;
}
it++;
}
}

void NotifyPeople()
{
list<ObserverPeople*>::iterator it = OP.begin();
while (it!=OP.end())
{
(*it)->Action();
it++;
}
}

};


class GuanYuOberver:public ObserverPeople
{
public:
GuanYuOberver(SubjectPeople*op):sp(*op)
{
sp.RegisterPeople(this);
}

public:
void Action()
{
cout<<"关羽给吕布一刀"<<endl;
}

protected:
SubjectPeople& sp;
};

class ZhangFeiOberver:public ObserverPeople
{
public:
ZhangFeiOberver(SubjectPeople*op):sp(*op)
{
sp.RegisterPeople(this);
}

public:
void Action()
{
cout<<"张飞给吕布一杖"<<endl;
}

protected:
SubjectPeople& sp;
};

class LiuBeiOberver:public ObserverPeople
{
public:
LiuBeiOberver(SubjectPeople*p):sp(*p)
{
sp.RegisterPeople(this);
}

public:
void Action()
{
cout<<"刘备给吕布一刀"<<endl;
}

protected:
SubjectPeople& sp;
};



int main()
{
LvBuSubject lvb;
GuanYuOberver gy(&lvb);
LiuBeiOberver liub(&lvb);
ZhangFeiOberver zf(&lvb);

lvb.NotifyPeople();
return 0;
}