代码实现
#include<iostream>
#include<string>
using namespace std;
#include<list>
class Observer
{
public:
virtual void Update() = 0;
};
class Subject
{
public:
void notify()
{
for (auto obs = observers.begin(); obs != observers.end(); obs++)
{
(*obs)->Update();
}
}
void addobj(Observer*ob)
{
observers.push_back(ob);
}
void removeobj(Observer *ob)
{
observers.remove(ob);
}
private:
list<Observer*>observers;
};
class ConSubject :public Subject
{
public:
void setState(int sta)
{
mState = sta;
}
int getState()
{
return mState;
}
private:
int mState;
};
class ConObserver :public Observer
{
public:
ConObserver(ConSubject *consub, string name ,string thing1,string thing2)
{
mSub = consub;
mThing1 = thing1;
mThing2 = thing2;
mName = name;
}
virtual void Update()
{
int state = mSub->getState();
if (state == 1)
{
cout << mName << " " << mThing1 << endl;
}
else
{
cout << mName << " " << mThing2 << endl;
}
}
private:
ConSubject *mSub;
string mThing1;
string mThing2;
string mName;
};
测试
#include"Observer.h"
int main()
{
ConSubject *cs = new ConSubject();
cs->setState(1);
Observer *co1 = new ConObserver(cs, "xianming", "have fun", "study");
Observer *co2 = new ConObserver(cs, "xiaohong", "eat", "drink");
cs->addobj(co1);
cs->addobj(co2);
cs->notify();
cs->setState(2);
cs->notify();
system("pause");
delete cs;
delete co1;
delete co2;
return 0;
}
|