C++二十三种设计模式之观察者模式

C++二十三种设计模式之观察者模式

一、组成

抽象主题 :维护观察者对象列表,具备通知功能。
具体主题 :实现维护观察者对象列表具体策略和通知功能。
抽象观察者 :为主题类提供更新接口。
具体观察者:实现更新接口。

二、目的

用于一个对象状态发生变化,所有依赖于它的对象都自动收到通知并进行更新。

三、缺点

1、资源浪费问题,存在大量观察者时,通知所有观察者会导致不需要此消息的观察者也收到这个消息。

2、通知顺序不确定,如果观察者之间需要存在先后收到通知的依赖关系时会有问题、

四、示例代码

javascript 复制代码
#include<iostream>
#include <vector>
#include <string>
using namespace std;

class WeatherObserver;//抽象观察者类
class WeatherApp;//具体观察者类
class AbstractWeatherStation;//抽象主题类
class WeatherStation;//具体主题类

class WeatherObserver {
public:
	virtual void updateWeather(const string weatherName) = 0;
};

class WeatherApp :public WeatherObserver {
public:
	explicit WeatherApp(const string appName) :appName(appName) {};
	void updateWeather(const string weatherName) {
		weatherCur = weatherName;
		printCurWeather();
	}
	void printCurWeather() {
		cout << "The current weather on thre " << appName << " app is " << weatherCur << endl;
	}
private:
	string weatherCur;
	string appName;
};

class AbstractWeatherStation {
public:
	virtual void addObserver(shared_ptr<WeatherObserver> observer) = 0;
	virtual void removeObserver(shared_ptr<WeatherObserver> observer) = 0;
	virtual void notifyObservers() = 0;
protected:
	vector<shared_ptr<WeatherObserver>> observers;
};

class WeatherStation :public AbstractWeatherStation {
public:
	void addObserver(shared_ptr<WeatherObserver> observer) {
		observers.push_back(observer);
	}
	void removeObserver(shared_ptr<WeatherObserver> observer) {
		observers.erase(remove(observers.begin(), observers.end(), observer), observers.end());
	}
	void notifyObservers() {
		for (const auto& observer : observers) {
			observer->updateWeather(weatherCur);
		}
	}
	void updateWeather(const string& weather) {
		weatherCur = weather;
		notifyObservers();
	}
private:
	vector<shared_ptr<WeatherObserver>> observers;
	string weatherCur;
};

int main() {
	shared_ptr<WeatherObserver> app1 = make_shared<WeatherApp>("天气宝app");
	shared_ptr<WeatherObserver> app2 = make_shared<WeatherApp>("气象通app");
	shared_ptr<WeatherStation> weatherStation = make_shared<WeatherStation>();
	weatherStation->addObserver(app1);
	weatherStation->addObserver(app2);
	weatherStation->updateWeather("晴天");

	weatherStation->removeObserver(app1);

	weatherStation->updateWeather("雨天");

}
相关推荐
郝学胜-神的一滴5 分钟前
Linux下的阻塞与非阻塞模式详解
linux·服务器·开发语言·c++·程序人生·软件工程
Samsong2 小时前
《C++ Primer Plus》读书笔记 第二章 开始学习C++
c++·后端
Rubisco..3 小时前
牛客周赛 Round 111
数据结构·c++·算法
hz_zhangrl3 小时前
CCF-GESP 等级考试 2025年9月认证C++四级真题解析
开发语言·c++·算法·程序设计·gesp·c++四级·gesp2025年9月
火山灿火山3 小时前
详解AVL树旋转操作实现
数据结构·c++
Seeing54 小时前
DS题目汇编
c++
2013编程爱好者4 小时前
计算时间复杂度
c++·算法·排序算法
西阳未落5 小时前
LeetCode——双指针(进阶)
c++·算法·leetcode
暴力求解5 小时前
c++类和对象(下)
开发语言·c++·算法
艾莉丝努力练剑6 小时前
【Linux指令 (二)】不止于入门:探索Linux系统核心与指令的深层逻辑,理解Linux系统理论核心概念与基础指令
linux·服务器·数据结构·c++·centos