本文介绍了C++中的观察者设计模式,通过代码示例展示了如何实现一个简单的观察者模式。观察者模式允许对象(观察者)订阅另一个对象(被观察者)的状态变化,并在状态变化时自动接收通知。文章通过subscriber
和observer
类的实现,演示了如何注册观察者、广播消息以及处理观察者的生命周期。该模式适用于需要解耦对象间依赖关系的场景,如事件处理系统。
观察者模式
观察者模式实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| #include <iostream> #include <memory> #include <string> #include <vector>
class observer; class subscriber : public std::enable_shared_from_this<subscriber> { public: subscriber(const std::string& user_name) : user_name_(user_name) { }
void callback(const std::string& str) { std::cout << user_name_ << ": " << str << std::endl; } private: std::string user_name_; };
class observer { public: void boardcast(const std::string& message) { for (auto it = vec.begin(); it != vec.end();) { auto sp = it->lock(); if (sp) { sp->callback(message); it++; } else { it = vec.erase(it); } } }
void regist(std::weak_ptr<subscriber> wp) { if (wp.lock()) { vec.push_back(wp); } } private: std::vector<std::weak_ptr<subscriber>> vec; };
int main() { auto ob = std::make_shared<observer>(); auto sp1 = std::make_shared<subscriber> ("subscriber1"); ob->regist(sp1->weak_from_this()); auto sp2 = std::make_shared<subscriber> ("subscriber2"); ob->regist(sp2->weak_from_this()); { auto sp3 = std::make_shared<subscriber> ("subscriber3"); ob->regist(sp3->weak_from_this()); auto sp4 = std::make_shared<subscriber> ("subscriber4"); ob->regist(sp4->weak_from_this()); ob->boardcast("start boardcast!"); } ob->boardcast("boardcast again!"); return 0; }
|