#pragma once
#include "stdafx.h"
#include<set>
#include<list>
#include<string>
#include<iostream>
#include<windows.h>
using namespace std;
//设计模式-观察者模式Observer
//定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象
//这个主题对象在状态发生变化时,会通知所有观察者对象,使他们能够自动更新自己。
class CObserver {//抽象接口
public:
virtual void Update() = 0;
};
class CSubject {//抽象通知者
private:
set<CObserver *> m_HashMemory;
public:
CSubject(){
m_HashMemory.clear();
}
~CSubject() {
for each(CObserver *i in m_HashMemory) {
delete i;
}
}
void Attach(CObserver *pObserver) {
m_HashMemory.insert(pObserver);
}
void Detach(CObserver *pObserver) {
m_HashMemory.erase(pObserver);
delete pObserver;
}
void Notify() {
for each(CObserver *i in m_HashMemory) {
i->Update();
}
}
};
class CConcreteSubjuct :public CSubject {//具体的通知着
private:
string m_strSubjectState;
public:
CConcreteSubjuct(const string &strName) {
m_strSubjectState = strName;
}
string GetName() {
return m_strSubjectState;
}
};
class ConcreteObserver :public CObserver{//具体的观察者
private:
string m_strName;
string m_strObserverState;
CConcreteSubjuct *m_pSubject;
public:
ConcreteObserver(CConcreteSubjuct *pSubject ,const string &strName) {
m_pSubject = pSubject;
m_strName = strName;
}
void Update() {
m_strObserverState = m_pSubject->GetName();
cout << "观察者" << m_strName << "的新状态是" << m_strObserverState << endl;
}
};
int main()
{
//一个前台,几个员工
CConcreteSubjuct *pQianTai = new CConcreteSubjuct("QianTai");
ConcreteObserver *pYuanGongA = new ConcreteObserver(pQianTai ,"YuanGongA");
ConcreteObserver *pYuanGongB = new ConcreteObserver(pQianTai, "YuanGongB");
ConcreteObserver *pYuanGongC = new ConcreteObserver(pQianTai, "YuanGongC");
pQianTai->Attach(pYuanGongA); pQianTai->Attach(pYuanGongB); pQianTai->Attach(pYuanGongC);
pQianTai->Notify();
pQianTai->Detach(pYuanGongB);
pQianTai->Notify();
getchar();
return 0;
}