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();
    }
}
相关推荐
QuantumStack2 小时前
【C++ 真题】P1104 生日
开发语言·c++·算法
天若有情6732 小时前
01_软件卓越之道:功能性与需求满足
c++·软件工程·软件
缘来是庄2 小时前
设计模式之访问者模式
java·设计模式·访问者模式
whoarethenext2 小时前
使用 C++/OpenCV 和 MFCC 构建双重认证智能门禁系统
开发语言·c++·opencv·mfcc
Jay_5153 小时前
C++多态与虚函数详解:从入门到精通
开发语言·c++
xiaolang_8616_wjl4 小时前
c++文字游戏_闯关打怪
开发语言·数据结构·c++·算法·c++20
FrostedLotus·霜莲5 小时前
C++主流编辑器特点比较
开发语言·c++·编辑器
hqxstudying5 小时前
Java创建型模式---单例模式
java·数据结构·设计模式·代码规范
花好月圆春祺夏安6 小时前
基于odoo17的设计模式详解---装饰模式
数据库·python·设计模式
fie88896 小时前
浅谈几种js设计模式
开发语言·javascript·设计模式