本文主要是介绍观察者模式C++,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
当对象间存在一对多的关系,当状态改变时,其他对象都得到通知,这就是观察者模式了。
观察者模式实现发布-订阅功能。如我们有个项目叫NGI,需要召开StanUp会议,会议上需求变更时需要通过所有参加会议的人员,我们就可以使用观察者模式,其UML图如下:
其代码实现如下:
#include <iostream>
#include <list>
#include <string>
using namespace std;class Observer
{
public:Observer(){}virtual ~Observer(){}virtual void Update(){}
};class Meeting
{
private:list<Observer*> m_obser;
protected:string m_state;
public:Meeting(){}virtual ~Meeting(){}void Attach(Observer* obser){m_obser.push_back(obser);}void Remove(Observer* pObser){m_obser.remove(pObser);}void Notify(){list<Observer*>::iterator iter;for (iter = m_obser.begin(); iter != m_obser.end(); iter++){(*iter)->Update();}}virtual void SetStatus(string s) { m_state = s; }virtual string GetStatus(void) { return m_state; }
};class StanUpMeeting : public Meeting
{
private:string m_name;
public:StanUpMeeting(string name) :m_name(name) {}~StanUpMeeting(){}void SetStatus(string s) { m_state = "StanUp Meeting Notify :" + m_name + s; }string GetStatus() { return m_state; }
};class NgiObserver :public Observer
{
private:string m_name;Meeting* m_meeting;
public:NgiObserver(string name, Meeting* meeting):m_name(name), m_meeting(meeting){}~NgiObserver() {}void Update(){string status = m_meeting->GetStatus();cout << m_name << "******" << status << endl;}
};int main(int argc, char** argv)
{Meeting *meeting = new StanUpMeeting("PM:");Observer *observer = new NgiObserver("Clark", meeting);meeting->Attach(observer);meeting->SetStatus("NGI Projrct requirment changed");meeting->Notify();delete meeting; delete observer;return 0;
}
以上代码在VS2015上运行通过。
这篇关于观察者模式C++的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!