• 我学cocos2d-x (两) 采用Delegate(信托)


    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();
            ...
    }


    版权声明:本文博主原创文章,博客,未经同意不得转载。

  • 相关阅读:
    使用kbmmw 生成REST 服务OpenAPI函数原型
    kbmmw 5.08 正式发布
    在datasnap 中使用unidac 访问数据(客户端)
    使用双引擎,让kbmmw 的客户端访问更方便
    使用kbmMWConfiguration 让 kbmmw smartservice 更聪明
    CE lua脚本
    error LNK2019: 无法解析的外部符号 __vsnwprintf,该符号在函数 "long __stdcall StringVPrintfWorkerW
    安装 directx sdk 出现 S1023 解决
    dx11的一些数据结构
    git 比较 change to be committed
  • 原文地址:https://www.cnblogs.com/bhlsheji/p/4913092.html
Copyright © 2020-2023  润新知