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

相关推荐
高晶10 小时前
CANopen 在 BMS 系统中的 C 语言实战指南
设计模式·程序员
博风11 小时前
13、设计模式应用举例:工厂方法模式:创建药品对象
设计模式·工厂方法模式
代钦塔拉13 小时前
【C++/Qt 进阶】设计模式系列(5):适配器模式——给“不兼容的接口“贴一层翻译膜
c++·qt·设计模式
bigbread1 天前
策略模式 + 工厂方法模式在项目中的实战应用
设计模式
高晶1 天前
C 语言实现 BMS 系统中 SPI 通信协议实战指南
设计模式·程序员
代钦塔拉1 天前
【C++/Qt 进阶】设计模式系列(2):工厂模式——从游戏角色到披萨店
c++·算法·设计模式
高晶1 天前
2A3 单端甲类功放从零制作全攻略:电路设计、焊接调试到煲机维护一站式指南
前端·设计模式
代钦塔拉1 天前
【C++/Qt 进阶】设计模式系列(4):原型模式——用“克隆“代替“重新构造“
c++·qt·设计模式
博风1 天前
11、设计模式应用举例:迭代器模式:使用多个集合存储对象
设计模式·迭代器模式
日和雫2 天前
面向对象与面向过程,谁才是“银弹”?
设计模式