其他分享
首页 > 其他分享> > C+;+;设计模式 - 观察者模式(Observer)

C+;+;设计模式 - 观察者模式(Observer)

作者:互联网

组件协作模式:

典型模式

Observer

动机(Motivation)

模式定义

安徽党政培训 www.tjganxun.cn 定义对象间的一种一对多(变化)的依赖关系,以便当一个对象(Subject)的状态发生改变时,所有依赖于它的对象都得到通知并自动更新。

结构

在这里插入图片描述

要点总结

cpp

#include<vector>#include<iostream>//观察者接口class ObserverInterface{public:virtual void dosomething() = 0;virtual ~ObserverInterface() {}};//被观察者接口class SubjectInterface {public:virtual void add(ObserverInterface*) = 0;virtual void remove(ObserverInterface*) = 0;virtual void notify() = 0;virtual ~SubjectInterface() {}};class Me :public SubjectInterface{public:void add(ObserverInterface* obr)override {observer.push_back(obr);}void remove(ObserverInterface* obr)override{auto pos = std::find(observer.begin(), observer.end(), obr);if (pos != observer.end()){observer.erase(pos);}}void notify()override{for (const auto& obs : observer){obs->dosomething();}}private:std::vector<ObserverInterface*>observer;};class Wife :public ObserverInterface {public:void dosomething() override {std::cout << "收到通知,开始做饭" << std::endl;}};class Daughter :public  ObserverInterface {public:void dosomething() override {std::cout << "爸爸快回来了,去开门!" << std::endl;}};int main() {Me me;ObserverInterface* wife = new Wife;ObserverInterface* daughter = new Daughter;//订阅消息me.add(wife);me.add(daughter);//发通知me.notify();delete wife;delete daughter;}

标签:observer,void,观察者,virtual,x2B,&#,ObserverInterface,设计模式,public
来源: https://blog.csdn.net/cmdos/article/details/123592435