设计模式:观察者模式(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()函数将观察者从观察者列表中移除,以停止接收通知。

相关推荐
wy_hhxx11 小时前
《Agent设计模式 图解可复用智能体架构》上篇内容整理
设计模式·架构·ai agent
AAA修煤气灶刘哥12 小时前
DSH Super-agent 双层架构:如何兼顾后台执行与持续响应
人工智能·后端·设计模式
用户624293196621 天前
告别 Electron 臃肿与 Wireshark 老化界面:用 Rust + Tauri 2.0 构建多总线网络与现场总线深度分析仪 Omni-Probe
设计模式
是2的10次方啊1 天前
设计模式与生活㉒:暖气热不热,得一间一间摸过去
设计模式
bigbread2 天前
迭代器模式-在区域健康档案导出中的实战应用
设计模式
装不满的克莱因瓶2 天前
设计模式之策略模式核心概念和应用场景
java·后端·设计模式·架构·系统架构·策略模式
是2的10次方啊2 天前
设计模式与生活㉑:一句“建议复查”,是好几句话拼出来的
设计模式
杯子不吃紫菜4 天前
LangGraph 体系实战(下):中断恢复、流式、子图与设计模式
单片机·嵌入式硬件·设计模式
是2的10次方啊4 天前
设计模式与生活⑳:楼里的事都找前台,你就再没见过师傅
设计模式
是2的10次方啊5 天前
设计模式与生活⑲:投影连不上,别急着换投影仪
设计模式