观察者模式(Observer Pattern)

时间:2024-12-10 20:19:08
#include <iostream> #include <vector> #include <unordered_map> #include <list> // 抽象观察者 class Observer { public: virtual void handleMessage(int messageID) = 0; virtual ~Observer() = default; }; // 具体观察者1:观察者感兴趣的是消息 1 和 2 class Observer1 : public Observer { public: void handleMessage(int messageID) override { if (messageID == 1 || messageID == 2) { std::cout << "Observer1 received message: " << messageID << std::endl; } else { std::cout << "Observer1 ignored message: " << messageID << std::endl; } } }; // 具体观察者2:观察者感兴趣的是消息 2 class Observer2 : public Observer { public: void handleMessage(int messageID) override { if (messageID == 2) { std::cout << "Observer2 received message: " << messageID << std::endl; } else { std::cout << "Observer2 ignored message: " << messageID << std::endl; } } }; // 具体观察者3:观察者感兴趣的是消息 1 和 3 class Observer3 : public Observer { public: void handleMessage(int messageID) override { if (messageID == 1 || messageID == 3) { std::cout << "Observer3 received message: " << messageID << std::endl; } else { std::cout << "Observer3 ignored message: " << messageID << std::endl; } } }; // 主题类 class Subject { private: // 维护消息ID到观察者列表的映射 std::unordered_map<int, std::list<Observer*>> observers; public: // 添加观察者 void addObserver(int messageID, Observer* observer) { observers[messageID].push_back(observer); } // 通知观察者 void notifyObservers(int messageID) { if (observers.find(messageID) != observers.end()) { for (Observer* observer : observers[messageID]) { observer->handleMessage(messageID); } } else { std::cout << "No observers for message: " << messageID << std::endl; } } }; // 主函数 int main() { Subject subject; Observer1 observer1; Observer2 observer2; Observer3 observer3; // 添加观察者 subject.addObserver(1, &observer1); subject.addObserver(2, &observer1); subject.addObserver(2, &observer2); subject.addObserver(1, &observer3); subject.addObserver(3, &observer3); // 测试通知 subject.notifyObservers(1); // 消息1通知 subject.notifyObservers(2); // 消息2通知 subject.notifyObservers(3); // 消息3通知 subject.notifyObservers(4); // 无人订阅的消息 return 0; }