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

相关推荐
怕浪猫6 小时前
一行命令复刻爆款视频,我把 Hypit 从安装跑到了出片
人工智能·设计模式·程序员
Zane19948 小时前
函数式编程里的函数,其实不是你天天写的那个函数——三大编程范式的边界在哪
设计模式
Zane19941 天前
策略模式现在该不该上?一次讲清楚过度设计和设计不足怎么找平衡
设计模式
她说..1 天前
常见设计模式-模板方法模式
java·spring·设计模式·springboot
xiaofeiyang1502 天前
第六章 · 桥接 — 三支毛笔,画出九种颜色
设计模式
Shadow(⊙o⊙)2 天前
OTOL设计模式 One Thread One Loop
服务器·网络·设计模式
sarasuki3 天前
如何让LLM 能在半夜偷偷打开网易云呢?
人工智能·设计模式·agent
小王师傅663 天前
【设计模式】装饰模式(四):框架源码实战——从 Java I/O 到 Spring 到 MyBatis
java·设计模式
执明wa3 天前
Android RecyclerView 多类型, 多种 Item
android·xml·开发语言·设计模式·android studio
sarasuki3 天前
如何让 Agent 获取更多的能力?插件 / 技能系统
人工智能·设计模式·agent