Cocos2d-x常用设计模式—观察者模式

发表于2017-12-21
评论0 1.6k浏览

观察者模式就是发送一个消息,让观察者执行某个动作,可用于数据传递,以可以用于消息传递。上一篇给大家介绍了Cocos2d-x的单例模式,下面我们继续介绍Cocos2d-x常用的设计模式,观察者模式。


一、动机及适用情况


二、类图


三、C++代码实现

3.1 头文件Observer.h

#include <iostream>  
#include <list>  
using namespace std;  
// 抽象类  
class Observer  
{  
public:  
    virtual void update() = 0;  
};  
class Subject  
{  
public:  
    virtual void attachObserver(Observer*) = 0;  
    virtual void detachObserver(Observer*) = 0;  
    virtual void notifyObservers() = 0;  
};  
// 具体类  
class ConcreteObeserver :public Observer  
{  
public:  
    ConcreteObeserver(Subject* pSubject);  
    virtual void update();  
private:  
    Subject* m_pSubject;  
};  
class ConcreteObserver2 : public Observer  
{  
public:  
    ConcreteObserver2(Subject* pSubject);  
    virtual void update();  
private:  
    Subject* m_pSubject;  
};  
class ConcreteSubject :public Subject  
{  
public:  
    virtual void attachObserver(Observer*);  
    virtual void detachObserver(Observer*);  
    virtual void notifyObservers();  
private:  
    list<Observer*> m_observer;  
};  


3.2 cpp文件Observer.cpp

#include "Observer.h"  
// 具体观察者的实现(定义)  
ConcreteObeserver::ConcreteObeserver(Subject* pSubject) :m_pSubject(pSubject)  
{  
}  
void ConcreteObeserver::update()  
{  
    cout << "override method update of ConcreteObserver class " << endl;  
}  
ConcreteObserver2::ConcreteObserver2(Subject* pSubject) :m_pSubject(pSubject)  
{  
}  
void ConcreteObserver2::update()  
{  
    cout << "override method update of ConcreteObserver2 class " << endl;  
}  
// 具体目标(被观察者)的实现  
void ConcreteSubject::attachObserver(Observer* observer)  
{  
    m_observer.push_back(observer);  
}  
void ConcreteSubject::detachObserver(Observer* observer)  
{  
    m_observer.remove(observer);  
}  
void ConcreteSubject::notifyObservers()  
{  
    for (auto it = m_observer.begin(); it != m_observer.end(); it++)// list<Observer*>::iterator it = m_observer.begin()  
    {  
        (*it)->update();  
    }  
}  
void main()  
{  
    // 创建具体目标和具体观察者实例  
    ConcreteSubject* pSubject = new ConcreteSubject();  
    ConcreteObeserver* pObserver = new ConcreteObeserver(pSubject);  
    ConcreteObserver2* pObserver2 = new ConcreteObserver2(pSubject);  
    // 目标对象注册观察者  
    pSubject->attachObserver(pObserver);  
    pSubject->attachObserver(pObserver2);  
    // 通知所有观察者  
    pSubject->notifyObservers();  
    // 释放资源  
    delete pSubject;  
    delete pObserver;  
    delete pObserver2;  
    cin.get();  
}  

3.3 执行结果


如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引