DesignPatterns/c++/observer.cc
2025-07-10 22:26:33 +08:00

35 lines
762 B
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* @name 观察者模式
* @brief: 定义对象间一对多的依赖关系
* @note 场景事件处理系统、消息订阅、MVC 模型更新视图
*/
#include <string>
#include <vector>
class Observer {
public:
virtual void update(const std::string& msg) = 0;
};
class Subject {
std::vector<Observer*> observers;
public:
void attach(Observer* o) { observers.push_back(o); }
void notify(const std::string& msg) {
for (auto o : observers) o->update(msg);
}
};
class ConcreteObserver : public Observer {
void update(const std::string& msg) override { /* 处理消息 */ }
};
// 使用
int main()
{
Subject subject;
subject.attach(new ConcreteObserver());
subject.notify("Event occurred!");
return 0;
}