设计模式:observer

结构图

代码

class Observer {
public:
    Observer();
    void update();
};
class Subject {
public:
    Subject() {}
    virtual ~Subject() {}
    void notifyAll() {
        MutexLockGuard guard(mutex);
        for (auto iter = observers_.begin(); iter != observers_.end();) {
            boost::shared_ptr obj(iter->lock());
            if (obj) {
                obj->update();
                ++iter;
            } else {
                iter = observers_.erase(iter);
            }
        }
    }
    void register_(boost::weak_ptr ob) {
        MutexLockGuard guard(mutex);
        observers_.push_back(ob);
    }

private:
    std::vector >  observers_;
    MutexLock mutex;
};

你可能感兴趣的:(c++,design-pattern,multi-thread)