C++设计模式浅识观察者模式

观察者模式(Observer):定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主体对象。这个主题对象在状态发生变化时,会通知所有观察者对象,使它们能够自动更新自己。

模式实现:

//观察者抽象基类
class Observer{
public:
    virtual void Update(int) = 0;
};
//主题、目标
class Subject{
public:
    virtual void Attach(Observer *) = 0;  //重视
    virtual void Detach(Observer *) = 0; //脱离
    virtual void Notify() = 0; //通知
};

class ConcreateObserver: public Observer{
private:
    Subject *m_pSubject;   //1.具体观察者,维护一个指向ConcreteSubject对象的引用2.存储有关状态,这些状态应与目标的状态保持一致
public:                     //3.实现Observer的更新接口以使自身状态与目标的状态保持一致
    ConcreateObserver(Subject *pSubject): m_pSubject(pSubject){}
    void Update(int value){
        std::cout << "ConcreateObserver get the update. New State: " << value << std::endl;
    }
};

class ConcreateObserver2: public Observer{
private:
    Subject *m_pSubject;
public:
    ConcreateObserver2(Subject *pSubject):m_pSubject(pSubject){}
    void Update(int value){
        std::cout << "ConcreateObserver2 get the update. New State: " << value << std::endl;
    }
};

//1.将有关状态存入各ConcreateObserver对象
//2.当它的状态发生改变时,向它的各个观察者发出通知
class ConcreateSubject: public Subject{
private:
    std::list<Observer *> m_ObserverList;
    int m_iState;
public:
    void Attach(Observer *pObserver);
    void Detach(Observer *pObserver);
    void Notify();

    void setState(int state){
        m_iState = state;
    }
};
void ConcreateSubject::Attach(Observer *pObserver){
    m_ObserverList.push_back(pObserver);
}
void ConcreateSubject::Detach(Observer *pObserver){
    m_ObserverList.remove(pObserver);
}
void ConcreateSubject::Notify(){
    std::list<Observer *>::iterator it = m_ObserverList.begin();
    while(it != m_ObserverList.end()){
        (*it)->Update(m_iState);
        ++it;
    }
}

客户端:

int main(){
    //Create Subject
    ConcreateSubject *pSubject = new ConcreateSubject();

    //Create Observer
    Observer *pObserver = new ConcreateObserver(pSubject);
    Observer *pObserver2 = new ConcreateObserver2(pSubject);

    //Change the state
    pSubject->setState(2);

    //Register the observer
    pSubject->Attach(pObserver);
    pSubject->Attach(pObserver2);

    pSubject->Notify();  //Output: ConcreateObserver get the update. New State: 2 
                                 //ConcreateObserver2 get the update. New State: 2

    //Unregister the observer
    pSubject->Detach(pObserver);

    pSubject->setState(3);

    pSubject->Notify();  //Output: ConcreateObserver2 get the update. New State: 3

    delete pObserver;
    delete pObserver2;
    delete pSubject;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值