cocos2d-x (二) 使用Delegate(委托)

来源:互联网 发布:intent的传递数据 编辑:程序博客网 时间:2024/06/05 13:30

原文链接:http://www.xuebuyuan.com/2122301.html

Delegate(委托)是什么

Delegate是ios开发中的一个概念,主要是为了让类A中的功能,放到类B中来实现,这样可以合理的把功能划分到不同的文件中进行实现,从而更好的实现模块的分离。如UIApplicationDelegate用于处理app启动、进入前台、进入后台等消息。
从设计模式的角度来看,Delegate属于组合模式,使用低耦合的代码,有利于编写可拓展的程序
cocos2d-x如何实现Delegate
我们看下如何在cocos2d-x中使用Delegate的实例。
1、定义一个接口类StatusDelegate,声明需要实现onGameStart、onGamePlaying、onGameEnd这三个方法:
class StatusDelegate {
public :
   
    virtual void onGameStart( void)
= 0;
   
    virtual void onGamePlaying( int score)
= 0;
   
    virtual void onGameEnd( int curScore, int bestScore)
= 0;
   
};

2、StatusLayer继承自StatusDelegate,实现onGameStart、onGamePlaying、onGameEnd这三个方法:

class StatusLayer:public Layer,public StatusDelegate{
     ...
     void onGameStart();
   
     void onGamePlaying( int score);
   
     void onGameEnd( int curScore, int bestScore);
     ...
}


3、在GameLayer中添加StatusDelegate变量:
class GameLayer public Layer{
     ...
     CC_SYNTHESIZE (StatusDelegate *,
delegator, Delegator);
     ...
}
这里CC_SYNTHESIZE这个宏用于添加StatusDelegate变量
#define CC_SYNTHESIZE (varType,
varName, funName)\
protected : varType varName;\
public virtual varType
get##funName(
 voidconst { return varName;
}\
public virtual void set##funName(varType
var){ varName = var; }


4、创建GameLayer时指定Delegate
auto gameLayer = GameLayer ::create();
if (gameLayer) {
     gameLayer->setDelegator(statusLayer);

}

5、调用Delegate的onGameStart()方法
if (this ->gameStatus
== 
GAME_STATUS_READY) {
        this->delegator->onGameStart();
        ...
}