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(
void
)
const
{
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();
...
}
版权声明:本文博主原创文章,博客,未经同意不得转载。
转载于:https://www.cnblogs.com/bhlsheji/p/4913092.html
相关资源:cocos2d-x游戏源码