知识巩固之观察者模式

 

百度百科:

观察者模式(有时又被称为模型-视图(View)模式、源-收听者(Listener)模式或从属者模式)是软件设计模式的一种。在此种模式中,一个目标物件管理所有相依于它的观察者物件,并且在它本身的状态改变时主动发出通知。这通常透过呼叫各观察者所提供的方法来实现。此种模式通常被用来实现事件处理系统。

说明: 区块链Bitcoin中信号处理使用的是boost里面的Signals2,而它实现了线程安全的观察者模式。

原理:被观察者(Appmanager/manager)触发条件后通知观察者(app/observer)处理。

相关:信号/槽(eg:boost 、Qt)   ;  函数回调;事件处理机制

code:

#include <list>
#include <string>
#include <iostream>
using namespace std;
//**************************************************************************
// the observer who get the notify
//**************************************************************************
class Observer{
public:
	Observer(){};
	virtual ~Observer(){};
	virtual void Update(){};
};

//**************************************************************************
// the abstract manager who send the notify
//**************************************************************************
class Manager{
public:
	Manager(){};	
	virtual ~Manager(){};
	void Attatch(Observer *observer){m_observers.push_back(observer);};
	void Remove(Observer *observer){m_observers.remove(observer);};
	void Notify(){
		cout<<m_status<<endl;
		list<Observer*>::iterator itor = m_observers.begin();
		for(; itor != m_observers.end(); itor++){
			(*itor)->Update();
		}
	};
	virtual void  SetStatus(string str){ m_status = str;};
	virtual string GetStatus(){return m_status;};
protected:
	list<Observer*> m_observers;	
	string m_status;
};

//**************************************************************************
// the specific manager who send the notify
//**************************************************************************
class AppManager : public Manager{
public:
	AppManager(string name):m_name(name){};
	~AppManager(){};
	void SetStatus(string str){m_status = "Notify : " + m_name + str;};
	string GetStatus(){return m_status;};
protected:
	string m_name;
};

//**************************************************************************
// the specific app who get the notify
//**************************************************************************
class App : public Observer{
public:
	App(string name):m_name(name){};
	~App(){};
	void Update(){
		cout<<"update the app : "<<m_name<<endl;
	};
private:
	string m_name;

};

//**************************************************************************
// the test main enter
//**************************************************************************
int main(){
	Manager *manager = new AppManager("MiddleControl");
	manager->SetStatus(" Observer design patterns");
	App *appMusic = new App("music");
	App *appTuner = new App("Tuner");
	App *appNavi  = new App("Navigate");
	App *appPhone = new App("Phone");

	manager->Attatch(appMusic);
	manager->Attatch(appTuner);
	manager->Attatch(appNavi);
	manager->Attatch(appPhone);

	manager->Notify();

	delete manager;
	delete appMusic;
	delete appTuner;
	delete appNavi;
	delete appPhone;
	
}

猜你喜欢

转载自blog.csdn.net/xuqiang918/article/details/81062164