C++ 设计模式:观察者模式

观察者模式是行为模式之一,它的一个对象的状态发生变化时能自动通知其它关联对象,自动刷新对象状态。

Qt中信号/槽函数机制就是观察者模式,信号只用进行函数声明,槽函数的参数要和信号的参数一致,这是因为编译器通过connect帮我们完成了信号函数的实现,Qt中的信号/槽函数功能的实现是基于回调函数的。

优点:

  • 遵循开闭原则
  • 可以运行时建立对象间的联系
  • 依赖倒置,让耦合的双方都依赖于抽象而不是依赖于具体

缺点:被观察者有很多直接或间接的观察者的话,通知所有观察者会耗费大量时间

示例代码:

cpp 复制代码
class observer;
class target{//观察对象
public:
    friend class observer;
    void Act();
    void set_action(string action){
        this->action=action;
        Act();
    }
    void Add_observer(observer*obs){
        dff.push_back(obs);
    }
    
private:
    string action;
    vector<observer*>dff;
};

class observer{//观察者
public:
    observer(target*tar,string id):tar(tar),id(id){}
    void update(){
        if(tar->action=="come"){
            cout<<id<<" action run"<<endl;
        }
        if(tar->action=="go"){
            cout<<id<<" action stop"<<endl;
        }
    }
private:
    target*tar;
    string id;
};
void target::Act(){
    for(observer* i:dff){
        i->update();
    }
}
相关推荐
十五年专注C++开发22 分钟前
C++之std::numeric_limits介绍
开发语言·c++·limits
拳里剑气1 小时前
C++算法:优先级队列
开发语言·c++·算法·优先级队列
从零开始的代码生活_1 小时前
C++ 模板入门:函数模板、类模板与实例化机制
开发语言·c++·后端
ttod_qzstudio3 小时前
【软考设计模式】策略模式:算法族的封装与动态切换精讲
设计模式·策略模式
咖啡八杯10 小时前
GoF设计模式——迭代器模式
java·后端·设计模式·迭代器模式
远离UE411 小时前
UE5 compute shader 原子加
开发语言·c++·ue5
C+-C资深大佬11 小时前
C++ 显式类型转换详解:static_cast、dynamic_cast、const_cast、reinterpret_cast
开发语言·c++
luj_176812 小时前
心形曲线轨迹控制三大关键技术
c语言·开发语言·c++·经验分享·算法
取地址符12 小时前
C++学习笔记(基于learn-cxx)(1)
c++·经验分享·笔记·学习
ttod_qzstudio12 小时前
【软考设计模式】外观模式:复杂子系统的“门面“封装与代码填空精讲
设计模式·外观模式