Observer design pattern in C++

前端 未结 7 990
礼貌的吻别
礼貌的吻别 2020-12-06 03:00

Is the observer design pattern already defined in STL (Like the java.util.Observer and java.util.Observable in Java) ?

7条回答
  •  死守一世寂寞
    2020-12-06 03:56

    Here is a reference implementation (from Wikipedia).

    #include 
    #include 
    #include 
    #include 
    
    class SupervisedString;
    class IObserver{
    public:
        virtual void handleEvent(const SupervisedString&) = 0;
    };
    
    
    class SupervisedString{ // Observable class
        std::string _str;
        std::map _observers;
    
        typedef std::map::value_type item;
    
        void _Notify(){
            BOOST_FOREACH(item iter, _observers){
                iter.second->handleEvent(*this);
            }
        }
    
    public:
        void add(IObserver& ref){
            _observers.insert(item(&ref, &ref));
        }
    
        void remove(IObserver& ref){
            _observers.erase(&ref);
        }
    
        const std::string& get() const{
            return _str;
        }
    
        void reset(std::string str){
            _str = str;
            _Notify();
        }
    };
    
    
    class Reflector: public IObserver{ // Prints the observed string into std::cout
    public:
        virtual void handleEvent(const SupervisedString& ref){
            std::cout<

提交回复
热议问题