学习设计模式时,最好的方式是通过实际的例程来加深理解。以下是一个简单的C++设计模式的例程,演示了观察者模式(Observer Pattern)的应用。观察者模式定义了一种一对多的依赖关系,使得当一个对象状态改变时,所有依赖它的对象都会得到通知并自动更新。
#include <iostream>
#include <vector>
#include <algorithm>// 抽象观察者类
class Observer {
public:virtual void update(const std::string& message) = 0;
};// 具体观察者类
class ConcreteObserver : public Observer {
public:ConcreteObserver(const std::string& name) : name(name) {}// 实现观察者的更新操作void update(const std::string& message) override {std::cout << name << " received message: " << message << std::endl;}private:std::string name;
};// 抽象主题类
class Subject {
public:virtual void addObserver(Observer* observer) = 0;virtual void removeObserver(Observer* observer) = 0;virtual void notifyObservers(const std::string& message) = 0;
};// 具体主题类
class ConcreteSubject : public Subject {
public:// 添加观察者void addObserver(Observer* observer) override {observers.push_back(observer);}// 移除观察者void removeObserver(Observer* observer) override {auto it = std::find_if(observers.begin(), observers.end(),[observer](Observer* obs) { return obs == observer; });if (it != observers.end()) {observers.erase(it);}}// 通知所有观察者void notifyObservers(const std::string& message) override {for (auto observer : observers) {observer->update(message);}}private:std::vector<Observer*> observers;
};int main() {// 创建具体主题ConcreteSubject subject;// 创建具体观察者ConcreteObserver observer1("Observer 1");ConcreteObserver observer2("Observer 2");ConcreteObserver observer3("Observer 3");// 添加观察者到主题subject.addObserver(&observer1);subject.addObserver(&observer2);subject.addObserver(&observer3);// 通知观察者subject.notifyObservers("Hello, observers!");// 移除一个观察者subject.removeObserver(&observer2);// 再次通知观察者subject.notifyObservers("Updated message!");return 0;
}