观察者模式是一对多的一种模式,当有状态发生变化的时候,所有监听这个事件的对象都会得到通知并做相应的更新。此模式特别适合事件的监听,对该事件感兴趣的可以注册监听,当不需要的适合就取消注册,事件发生适合,广播通知所有注册对象。我们结合智能指针来实现一个简单的观察者模式,智能指针可以方便的判断注册对象是否还存在,可以有效的避免对象已经不存在了还调用
class IObject {
public:
virtual void update() = 0;
};
class object_test1 : public IObject {
public:
void update() {
std::cout << "object_test1 update" << std::endl;
}
};
class object_test2 : public IObject {
public:
void update() {
std::cout << "object_test2 update" << std::endl;
}
};
class object_test3 : public IObject {
public:
void update() {
std::cout << "object_test3 update" << std::endl;
}
};
class subject_test {
public:
subject_test() {}
~subject_test() {}
public:
void register_object(int id, std::weak_ptr<IObject> ob_ptr) {
map_test_[id] = ob_ptr;
}
void unreg_object(int id) {
auto it = map_test_.find(id);
if (it != map_test_.end()) {
map_test_.erase(it);
}
}
void notify() {
for (auto it = map_test_.begin(); it != map_test_.end(); ) {
std::shared_ptr<IObject> sp = it->second.lock();
if (sp) {
sp->update();
it++;
} else {
std::cout << "notify msg, but it's invalid, so erase it" << std::endl;
it = map_test_.erase(it);
}
}
}
private:
std::map<int, std::weak_ptr<IObject> > map_test_;
};
int main()
{
subject_test st;
{
std::shared_ptr<IObject> p1 = std::make_shared<object_test1>();
std::shared_ptr<IObject> p2 = std::make_shared<object_test2>();
std::shared_ptr<IObject> p3 = std::make_shared<object_test3>();
st.register_object(1, std::weak_ptr<IObject>(p1));
st.register_object(2, std::weak_ptr<IObject>(p2));
st.register_object(3, std::weak_ptr<IObject>(p3));
st.notify();
st.unreg_object(1);
}
st.notify();
}
object_test1 update
object_test2 update
object_test3 update
notify msg, but it's invalid, so erase it
notify msg, but it's invalid, so erase it