observer 简单实例

#include "Publicinc.hpp"

class  Observer
{
public:
    virtual  ~Observer() { }
    virtual  void  Update(int n) = 0;
};

class  Subject
{
    typedef  std::vector  ObserverList;
    typedef  ObserverList::iterator  ObserverIterator;
public:
    void  AddObserver(Observer* pObserver)
    {
        m_observers.push_back(pObserver);
    }

    void  RemoveObserver(Observer* pObserver)
    {
        ObserverIterator iter = std::find(m_observers.begin(), m_observers.end(), pObserver);
        if (iter != m_observers.end()) {
            m_observers.erase(iter);
            delete pObserver;
        }
    }

    void  Notify(int n)
    {
        for (Observer* pObserver : m_observers) {
            pObserver->Update(n);
        }
    }

    ~Subject()
    {
        for (auto& observer : m_observers) {
            delete observer;
            observer = nullptr;
        }
    }

private:
    ObserverList  m_observers;
};


class  ConcreteObserver1 : public Observer
{
public:
    virtual  void  Update(int n)
    {
        printf("concrete observer 1 receive param is {%d}\n", n);
    }
};

class  ConcreteObserver2 : public Observer
{
public:
    virtual  void  Update(int n)
    {
        printf("concrete observer 2 receive param is {%d}\n", n);
    }
};

void  TestSubjectObserver()
{
    Subject  subject;
    Observer* pObserver1 = new ConcreteObserver1();
    Observer* pObserver2 = new ConcreteObserver1();
    Observer* pObserver3 = new ConcreteObserver2();
    Observer* pObserver4 = new ConcreteObserver2();

    subject.AddObserver(pObserver1);
    subject.AddObserver(pObserver2);
    subject.AddObserver(pObserver3);
    subject.AddObserver(pObserver4);

    subject.RemoveObserver(pObserver1);

    subject.Notify(100);
}

你可能感兴趣的:(C++)