c++实现观察者模式

前言

我觉得这是最有意思的模式,其中一个动,另外的自动跟着动。发布-订阅,我觉得很巧妙。

代码

头文件

cpp 复制代码
#pragma once
#include<vector>
#include<string>
#include<iostream>

// 抽象观察者
class Aobserver
{
public:
	virtual void update(std::string& updated_state) = 0;
};


// 抽象通知者
class Asubject
{
protected:
	std::vector<Aobserver*> _pObservers;

	bool whetherRegist(Aobserver* p_observer)
	{
		for (auto it : _pObservers) {
			if (it == p_observer) return true;
		}
		return false;
	}

public:
	virtual void registObserver(Aobserver* p_observer) = 0;
	virtual void detachObserver(Aobserver* p_observer) = 0;
	virtual void notify(const std::string& teacher_name) = 0;

};


// 具体通知者
class Csubject1 : public Asubject
{
private:
	std::string _subjectName;

public:
	Csubject1(const std::string& subject_name) :_subjectName(subject_name) {}

	// 注册观察者
	void registObserver(Aobserver* p_observer) override
	{
		if (p_observer!=nullptr && whetherRegist(p_observer) == false) {
			_pObservers.push_back(p_observer);
		}
	}

	void detachObserver(Aobserver* p_observer) override
	{
		if (p_observer != nullptr)
		{
			for (auto it : _pObservers) {
				if (it == p_observer) {
					_pObservers.erase(
						std::remove(_pObservers.begin(),_pObservers.end(),it),
						_pObservers.end());
				}
			}
		}
	}

	void notify(const std::string& teacher_name) override
	{
		std::string notify_state = _subjectName + " say: "+ teacher_name +" is coming!";
		for (auto it : _pObservers) {
			it->update(notify_state);
		}
	}
};

// 具体观察者
class Hablee : public Aobserver
{
private:
	void cancleReading(std::string& updated_state)
	{
		std::cout << updated_state;
		std::cout << " you should stop reading" << std::endl;
	}

public:
	void update(std::string& updated_state) override
	{
		this->cancleReading(updated_state);
	}

};

class Yuki : public Aobserver
{
private:
	void canclePlayingGuitar(std::string& updated_state)
	{
		std::cout << updated_state;
		std::cout << " you should stop plaing guitar" << std::endl;
	}

public:
	void update(std::string& updated_state) override
	{
		this->canclePlayingGuitar(updated_state);
	}
};

main.cpp

cpp 复制代码
#include<iostream>
#include"Aobserver.h"


int main()
{
	Csubject1 wzq("wangZhaoQi"); // 通知者
	
	Hablee lhb;	
	wzq.registObserver(&lhb);

	Yuki wwy;
	wzq.registObserver(&wwy);

	wzq.notify("lyj");
	wzq.notify("xiaoZhang");

	wzq.detachObserver(&lhb);
	wzq.notify("lyj");
	
	return 0;
}
相关推荐
爱上妖精的尾巴38 分钟前
6-4 WPS JS宏 不重复随机取值应用
开发语言·前端·javascript
小鸡吃米…2 小时前
Python 列表
开发语言·python
kaikaile19952 小时前
基于C#实现一维码和二维码打印程序
开发语言·c#
我不是程序猿儿3 小时前
【C#】画图控件的FormsPlot中的Refresh功能调用消耗时间不一致缘由
开发语言·c#
rit84324993 小时前
C# Socket 聊天室(含文件传输)
服务器·开发语言·c#
kk哥88993 小时前
C++ 对象 核心介绍
java·jvm·c++
helloworddm3 小时前
WinUI3 主线程不要执行耗时操作的原因
c++
嘉琪0013 小时前
Vue3+JS 高级前端面试题
开发语言·前端·javascript
xunyan62343 小时前
面向对象(下)-接口的理解
java·开发语言
遥不可及~~斌3 小时前
Java 面试题集 -- 001
java·开发语言