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();
    }
}
相关推荐
6Hzlia5 分钟前
【Hot 100 刷题计划】 LeetCode 199. 二叉树的右视图 | C++ DFS 逆序遍历
c++·leetcode·深度优先
-Marks-9 分钟前
【C++编程】STL简介 --- (是什么 | 版本发展历程 | 六大组件 | 重要性缺陷以及如何学习)
开发语言·c++·学习·stl·stl版本
CoderCodingNo1 小时前
【信奥业余科普】C++ 的奇妙之旅 | 12:程序的交互与加工——数据的输入与算术运算
开发语言·c++
yx868xy1 小时前
Cuda加速直线拟合
c++·cuda
蜗牛在听雨2 小时前
基于 C++ 的 UG/NX 二次开发环境配置
c++·二次开发·ug
SimpleLearingAI2 小时前
C++虚函数详解
开发语言·c++
小柯博客3 小时前
STM32MP2安全启动技术深度解析
c语言·c++·stm32·嵌入式硬件·安全·开源·github
cpp_25013 小时前
P1832 A+B Problem(再升级)
数据结构·c++·算法·动态规划·题解·洛谷·背包dp
geovindu3 小时前
go: Proxy Pattern
开发语言·后端·设计模式·golang·代理模式