C++实现观察者模式
时间: 2023-06-29 20:20:54 浏览: 85
观察者模式是一种行为设计模式,它允许一个对象(主题)在其状态发生改变时,向其依赖对象(观察者)发送通知。以下是C++实现观察者模式的示例代码:
```
#include <iostream>
#include <vector>
class Observer {
public:
virtual void update() = 0;
};
class Subject {
private:
std::vector<Observer*> observers;
public:
void attach(Observer* observer) {
observers.push_back(observer);
}
void detach(Observer* observer) {
for (auto it = observers.begin(); it != observers.end(); ++it) {
if (*it == observer) {
observers.erase(it);
return;
}
}
}
void notify() {
for (auto observer : observers) {
observer->update();
}
}
};
class ConcreteObserver : public Observer {
public:
void update() override {
std::cout << "ConcreteObserver received update." << std::endl;
}
};
int main() {
Subject subject;
ConcreteObserver observer1, observer2;
subject.attach(&observer1);
subject.attach(&observer2);
subject.notify();
subject.detach(&observer1);
subject.notify();
return 0;
}
```
在此示例中,观察者模式由三个类组成:`Observer`,`Subject`和`ConcreteObserver`。`Observer`是一个抽象基类,其派生类需要实现`update`方法以响应主题的更改。`Subject`是主题类,它维护一个观察者列表,并提供方法以添加、删除和通知观察者。`ConcreteObserver`是一个具体的观察者类,它实现了`update`方法以响应主题的更改。
在`main`函数中,我们创建一个主题对象和两个观察者对象。我们附加这些观察者对象到主题对象上,然后调用`notify`方法以通知所有观察者对象。然后,我们从主题对象上分离一个观察者对象,并再次调用`notify`方法以通知其余观察者对象。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)