2019-11-06 13:36:28 +00:00
|
|
|
|
#define __DEMO_H__
|
|
|
|
|
#ifdef __DEMO_H__
|
|
|
|
|
|
|
|
|
|
using namespace std;
|
|
|
|
|
#include <list>
|
|
|
|
|
|
|
|
|
|
// <20><><EFBFBD><EFBFBD><EFBFBD>۲<EFBFBD><DBB2><EFBFBD>
|
|
|
|
|
class Observer
|
|
|
|
|
{
|
|
|
|
|
public:
|
2021-04-04 13:09:08 +00:00
|
|
|
|
virtual ~Observer() {}
|
2019-11-06 13:36:28 +00:00
|
|
|
|
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ӧ<EFBFBD><D3A6><EFBFBD>·<EFBFBD><C2B7><EFBFBD>
|
|
|
|
|
virtual void update() = 0;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// <20><><EFBFBD><EFBFBD><EFBFBD>۲<EFBFBD><DBB2><EFBFBD>
|
|
|
|
|
class ConcreteObserver:public Observer
|
|
|
|
|
{
|
|
|
|
|
public:
|
|
|
|
|
// ʵ<><CAB5><EFBFBD><EFBFBD>Ӧ<EFBFBD><D3A6><EFBFBD>·<EFBFBD><C2B7><EFBFBD>
|
|
|
|
|
void update(){
|
|
|
|
|
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// <20><><EFBFBD><EFBFBD>Ŀ<EFBFBD><C4BF>
|
|
|
|
|
class Subject
|
|
|
|
|
{
|
|
|
|
|
public:
|
2021-04-04 13:09:08 +00:00
|
|
|
|
virtual ~Subject() {}
|
2019-11-06 13:36:28 +00:00
|
|
|
|
// <20><><EFBFBD>ӹ۲<D3B9><DBB2><EFBFBD>
|
|
|
|
|
void attach(Observer* obs){
|
|
|
|
|
obsList.push_back(obs);
|
|
|
|
|
}
|
|
|
|
|
// <20>Ƴ<EFBFBD><C6B3>۲<EFBFBD><DBB2><EFBFBD>
|
|
|
|
|
void detach(Observer* obs){
|
|
|
|
|
obsList.remove(obs);
|
|
|
|
|
}
|
|
|
|
|
// <20><><EFBFBD><EFBFBD>֪ͨ<CDA8><D6AA><EFBFBD><EFBFBD>
|
|
|
|
|
virtual void notify() = 0;
|
|
|
|
|
protected:
|
|
|
|
|
// <20>۲<EFBFBD><DBB2><EFBFBD><EFBFBD>б<EFBFBD>
|
|
|
|
|
list<Observer*>obsList;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// <20><><EFBFBD><EFBFBD>Ŀ<EFBFBD><C4BF>
|
|
|
|
|
class ConcreteSubject :public Subject
|
|
|
|
|
{
|
|
|
|
|
public:
|
|
|
|
|
// ʵ<><CAB5>֪ͨ<CDA8><D6AA><EFBFBD><EFBFBD>
|
|
|
|
|
void notify(){
|
|
|
|
|
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
|
|
|
|
// <20><><EFBFBD><EFBFBD>֪ͨ<CDA8>۲<EFBFBD><DBB2>߶<EFBFBD><DFB6><EFBFBD>
|
|
|
|
|
for (int i = 0; i < obsList.size(); i++){
|
|
|
|
|
obsList[i]->update();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// <20>ͻ<EFBFBD><CDBB>˴<EFBFBD><CBB4><EFBFBD>ʾ<EFBFBD><CABE>
|
|
|
|
|
int main()
|
|
|
|
|
{
|
|
|
|
|
Subject *sub = new ConcreteSubject();
|
|
|
|
|
Observer *obs = new ConcreteObserver();
|
|
|
|
|
sub->attach(obs);
|
|
|
|
|
sub->notify();
|
|
|
|
|
return 0;
|
|
|
|
|
}
|
|
|
|
|
#endif
|