设计模式:观察者模式(C++实现)

观察者模式(Observer Pattern)是一种设计模式,用于定义对象之间的一对多依赖关系,当一个对象(称为主题或可观察者)的状态发生变化时,它的所有依赖对象(称为观察者)都会收到通知并进行相应的更新。

以下是一个简单的C++观察者模式的示例:

cpp 复制代码
#include <iostream>
#include <vector>
#include <algorithm>

// 观察者基类
class Observer
{
public:
    virtual void update(int value) = 0;
};

// 具体观察者类
class ConcreteObserver : public Observer
{
private:
    int number;

public:
    ConcreteObserver(int number)
    {
        this->number = number;
    }
    void update(int value) override
    {
        std::cout << "Current number: " << this->number << std::endl;
        std::cout << "new value: " << value << std::endl;
    }
};

// 主题类
class Subject
{
private:
    std::vector<Observer *> observers; // 观察者列表
    int value;

public:
    Subject(int value)
    {
        this->value = value;
    }
    void attach(Observer *observer)
    {
        observers.push_back(observer);
    }
    void detach(Observer *observer)
    {
        // 从观察者列表中移除观察者
        auto it = std::find(observers.begin(), observers.end(), observer);
        if (it != observers.end())
        {
            observers.erase(it);
        }
    }
    void notify()
    {
        // 通知所有观察者进行更新
        for (auto observer : observers)
        {
            observer->update(this->value);
        }
    }

    void changeValue(int newValue)
    {
        this->value = newValue;
    }
};

int main()
{
    Subject subject(0);
    ConcreteObserver observer1(1);
    ConcreteObserver observer2(2);
    subject.attach(&observer1);
    subject.attach(&observer2);
    subject.notify(); // 所有观察者都会收到通知并进行更新
    subject.changeValue(10);
    subject.detach(&observer1);
    subject.notify(); // 只有observer2会收到通知
    return 0;
}

运行结果:

bash 复制代码
Current number: 1
new value: 0
Current number: 2
new value: 0
Current number: 2
new value: 10

在上述示例中,Observer是观察者的基类,定义了一个纯虚函数update(),用于在观察者收到通知时进行更新操作。ConcreteObserver是具体的观察者类,实现了update()函数。

Subject是主题类,维护一个观察者列表,并提供了attach()、detach()和notify()函数。attach()用于将观察者添加到观察者列表中,detach()用于从观察者列表中移除观察者,notify()用于通知所有观察者进行更新操作。

在main()函数中,创建了一个主题对象subject和两个观察者对象observer1和observer2。通过attach()函数将观察者添加到主题的观察者列表中,然后通过notify()函数通知所有观察者进行更新。可以通过detach()函数将观察者从观察者列表中移除,以停止接收通知。

相关推荐
晚安code5 小时前
设计模式入门:吃透 SOLID 原则与迪米特法则,再学 5 个高频模式
后端·设计模式
染指11109 小时前
135.Agent-多Agent框架-LangChain多智能体(SubAgents子代理)
数据库·人工智能·设计模式·langchain·agent·agents
路弥行至1 天前
【Head First 设计模式】第 2 章:观察者模式 —— 用现代 C++ 重新解读“交互对象的松耦合
c++·经验分享·笔记·观察者模式·设计模式·入门教程·headfirst
YYYing.1 天前
【设计模式系列 (九) 】装饰器模式
c++·后端·设计模式·装饰器模式·c/c++
沫璃染墨1 天前
《从零入门Linux系统篇(五十六):线程篇·九——生产者消费者模型:从条件变量到BlockingQueue实现》
linux·服务器·c++·驱动开发·设计模式·架构·系统架构
c萱2 天前
AI产品经理——01基础认知篇
设计模式·prompt·aigc·产品经理·ai编程·gitcode·ai-native
YYYing.2 天前
【设计模式系列 (八) 】组合模式
c++·后端·设计模式·组合模式·c/c++
geovindu3 天前
rust: Composite Pattern
开发语言·后端·设计模式·rust·组合模式
YYYing.3 天前
【设计模式系列 (七) 】桥接模式
c++·后端·设计模式·桥接模式
阿狗童鞋4 天前
设计模式实战指南
设计模式