结构图

clipboard.png

代码

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<Observer> obj(iter->lock());
            if (obj) {
                obj->update();
                ++iter;
            } else {
                iter = observers_.erase(iter);
            }
        }
    }
    void register_(boost::weak_ptr<Observer> ob) {
        MutexLockGuard guard(mutex);
        observers_.push_back(ob);
    }

private:
    std::vector<boost::weak_ptr<Observer> >  observers_;
    MutexLock mutex;
};

shiyang6017
164 声望60 粉丝