设计模式——观察者模式(C++实现)

设计模式——观察者模式(C++实现)

设计模式——观察者模式(C++实现)

 #include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <string> using namespace std; class STSubject; //观察者
class STObserver
{
public:
virtual void Update() = ;
}; class STConcreteObserverA: public STObserver
{
public:
virtual void Update()
{
cout<< "ConcreteObserverA Get Subject: "<< endl;
}
}; class STConcreteObserverB: public STObserver
{
public:
virtual void Update()
{
cout<< "ConcreteObserverB Get Subject: "<< endl;
}
}; //目标
class STSubject
{
public:
void Attach(STObserver* pstObserver)
{
m_vecObj.push_back(pstObserver);
}
void Detach(STObserver* pstObserver)
{
typeof(m_vecObj.begin()) it = find(m_vecObj.begin(), m_vecObj.end(), pstObserver);
if (it != m_vecObj.end())
m_vecObj.erase(it);
}
void Notify()
{
for (size_t i = ; i < m_vecObj.size(); i++)
{
m_vecObj[i]->Update();
}
} virtual string GetName() = ; private:
vector<STObserver*> m_vecObj;
}; class STConcreteSubjectA: public STSubject
{
public:
virtual string GetName()
{
return "ConcreteSubjectA";
} }; int main(int argc, char* argv[])
{
STSubject* pstSubjectA = new STConcreteSubjectA();
STObserver* pstObserverA = new STConcreteObserverA();
STObserver* pstObserverB = new STConcreteObserverB(); pstSubjectA->Attach(pstObserverA);
pstSubjectA->Attach(pstObserverB); pstSubjectA->Notify(); pstSubjectA->Detach(pstObserverB);
pstSubjectA->Notify(); return ;
}
//////////////////////////////////
[root@ ~/learn_code/design_pattern/12_observer]$ ./observer
ConcreteObserverA Get Subject:
ConcreteObserverB Get Subject:
ConcreteObserverA Get Subject:
上一篇:redis安装及启动


下一篇:NOsql总结