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();
    }
}
相关推荐
geovindu3 小时前
rust:Memento Pattern(续)
开发语言·后端·设计模式·rust·行为模式·备忘录模
电子IT笔记3 小时前
老MES登录改造:弱密码和暴破一起治
设计模式
半杯咖啡半行码5 小时前
C++11核心特性详解:从C++11到C++20 的现代C++指南
开发语言·c++
牧瀬クリスだ5 小时前
单例模式终极指南:从入门到防破坏
单例模式·设计模式
All for pursuit.6 小时前
【位运算-3】136.只出现一次的数字
数据结构·c++·算法·leetcode
C++ 老炮儿的技术栈7 小时前
std::atomic 是什么
linux·c语言·网络·c++·visual studio
All for pursuit.8 小时前
【完结】LeetCodeHot100题 详细解题过程及代码汇总
数据结构·c++·算法·leetcode
重生之小比特8 小时前
【算法拾光】双指针|移动零 + 复写零
数据结构·c++·算法
多弗朗皮卡丘9 小时前
C++异常
开发语言·c++·异常