觀察者模式(Observer)定義對象間的一種一對多的依賴關(guān)系,當(dāng)一個對象的狀態(tài)發(fā)生改變時, 所有依賴于它的對象都得到通知并被自動更新。
假設(shè)貓大叫一聲,所有的老鼠開始逃跑,這時,老鼠是觀察者,貓是被觀察者,當(dāng)被觀察者狀態(tài)改變(貓大叫一聲)時將發(fā)送一個通知給其所有觀察者,結(jié)構(gòu)圖為:

實現(xiàn)代碼:
//Observer.h
class Observer
{
public:
virtual ~Observer();
virtual void Update() = 0;
protected:
Observer();
};
//Observer.cpp
#include "stdafx.h"
#include "Observer.h"
Observer::Observer()
{
}
Observer::~Observer()
{
}
//Mouse.h
#include "Observer.h"
class Mouse : public Observer
{
public:
Mouse(char*);
virtual ~Mouse();
void Update();
private:
char* m_pName;
};
//Mouse.cpp
#include "stdafx.h"
#include "Mouse.h"
#include <iostream>
using namespace std;
Mouse::Mouse(char* pName)
{
this->m_pName = pName;
}
Mouse::~Mouse()
{
}
void Mouse::Update()
{
cout << this->m_pName << "聽到貓叫,開始逃跑" << endl;
}
//Subject.h
#include <vector>
class Observer;
class Subject
{
public:
virtual ~Subject();
virtual void Attach(Observer*);
virtual void Detach(Observer*);
virtual void Notify();
protected:
Subject();
std::vector<Observer*> m_vObservers;
};
//Subject.cpp
#include "stdafx.h"
#include "Subject.h"
#include "Observer.h"
#include <algorithm>
#include <functional>
using namespace std;
Subject::Subject()
{
}
Subject::~Subject()
{
}
void Subject::Attach(Observer* pObs)
{
m_vObservers.push_back(pObs);
}
void Subject::Detach(Observer* pObs)
{
m_vObservers.erase(remove_if(m_vObservers.begin(), m_vObservers.end(), bind1st(equal_to<Observer*>(), pObs)));
}
void Subject::Notify()
{
vector<Observer*>::iterator it = m_vObservers.begin();
for( ; it != m_vObservers.end(); ++it )
{
(*it)->Update();
}
}
//Cat.h
#include "Subject.h"
class Cat : public Subject
{
public:
Cat();
virtual ~Cat();
void Cry();
};
//Cat.cpp
#include "stdafx.h"
#include "Cat.h"
#include <iostream>
using namespace std;
Cat::Cat()
{
}
Cat::~Cat()
{
}
void Cat::Cry()
{
cout << "貓大叫一聲" << endl;
this->Notify();
}
//main.cpp
#include "stdafx.h"
#include "Cat.h"
#include "Mouse.h"
int main(int argc, char* argv[])
{
Observer* pMouseA = new Mouse("白鼠");
Observer* pMouseB = new Mouse("黑鼠");
Cat cat;
cat.Attach(pMouseA);
cat.Attach(pMouseB);
cat.Cry();
return 0;
}
運行結(jié)果:
貓大叫一聲
白鼠聽到貓叫,開始逃跑
黑鼠聽到貓叫,開始逃跑