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();
    }
}
相关推荐
hellokandy1 天前
C++ 如何知道程序最多可以申请多少内存
c++·vector·cin·cout
凯子坚持 c1 天前
Protocol Buffers C++ 进阶数据类型与应用逻辑深度解析
java·服务器·c++
jiunian_cn1 天前
【C++】IO流
开发语言·c++
Geoking.1 天前
【设计模式】23 种设计模式全景总结
设计模式
CoderCodingNo1 天前
【GESP】C++六级考试大纲知识点梳理, (7) 栈与队列
开发语言·c++
超级大福宝1 天前
【力扣200. 岛屿数量】的一种错误解法(BFS)
数据结构·c++·算法·leetcode·广度优先
Frank_refuel1 天前
C++之继承
开发语言·c++
哪有时间简史1 天前
C++程序设计
c++
sg_knight1 天前
工厂方法模式(Factory Method)
java·服务器·python·设计模式·工厂方法模式·工厂模式
%xiao Q1 天前
GESP C++四级-216
java·开发语言·c++