一、概述
????????觀察者模式定義對象間的一種一對多的依賴關系,當一個對象的狀態(tài)發(fā)生改變時,所有依賴于它的對象都得到通知并被自動更新。
二、示例代碼
#include <list>
class Subject;
class Observer
{
public:
?? ?virtual ~Observer();
?? ?virtual void Update(Subject* theChangedSubject) = 0;
protected:
?? ?Observer();
};
class Subject
{
public:
?? ?virtual ~Subject(){}
?? ?virtual void Attach(Observer* o)
?? ?{
?? ??? ?_observers->push_back(o);
?? ?}
?? ?virtual void Detach(Observer* o)
?? ?{
?? ??? ?_observers->remove(o);
?? ?}
?? ?virtual void Notity()
?? ?{
?? ??? ?std::list<Observer*>::iterator it = _observers->begin();
?? ??? ?while (it != _observers->end())
?? ??? ?{
?? ??? ??? ?(*it)->Update(this);
?? ??? ??? ?++it;
?? ??? ?}
?? ?}
protected:
?? ?Subject();
private:
?? ?std::list<Observer*> *_observers;
};
上述代碼是一個簡單的觀察者設計模式代碼,邏輯清晰,但這種不能夠通用,只能對特定的觀察者才有效,即必須是Observer抽象類的派生類才行,并且這個觀察者還不能帶參數(shù),而且接口參數(shù)不支持變化,那么觀察者將不能應付接口的變化。那么應該如何解決這個問題呢?可以使用C++11一些特性來改變。
class NonCopyable
{
protected:
?? ?NonCopyable() = default;
?? ?~NonCopyable() = default;
?? ?NonCopyable(const NonCopyable&) = delete; //禁用拷貝構造
?? ?NonCopyable& operator = (const NonCopyable&) = delete; //禁用賦值構造
};
#include <iostream>
#include <string>
#include <functional>
#include <map>
using namespace std;
template<typename Func>
class Events : NonCopyable
{
public:
?? ?Events(){}
?? ?~Events(){}
?? ?//注冊觀察者,支持右值
?? ?int Connect(Func&& f)
?? ?{
?? ??? ?return Assgin(f);
?? ?}
?? ?//注冊觀察者
?? ?int Connect(Func& f)
?? ?{
?? ??? ?return Assgin(f);
?? ?}
?? ?//移除觀察者
?? ?void Disconnect(int key)
?? ?{
?? ??? ?m_connections.erase(key);
?? ?}
private:
?? ?//保存觀察者并分配觀察者編號
?? ?template<typename F>
?? ?int Assgin(F&& f)
?? ?{
?? ??? ?int k = m_observerId++;
?? ??? ?m_connections.emplace(k, std::forward<F> (f));
?? ?}
?? ?int m_observerId = 0;
?? ?std::map<int, Func> m_connections;
};文章來源:http://www.zghlxwxcb.cn/news/detail-627397.html
C++11實現(xiàn)的觀察者,內(nèi)部為了一個泛型函數(shù)列表,觀察者只需要將觀察者函數(shù)進行注冊進來即可,消除了繼承導致的強耦合。通知接口使用了可變參數(shù)模板,支持任意參數(shù),這就消除了接口變化的影響。文章來源地址http://www.zghlxwxcb.cn/news/detail-627397.html
到了這里,關于C++設計模式行為型之觀察者模式的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!