zoukankan      html  css  js  c++  java
  • 我学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();
            ...
    }


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

  • 相关阅读:
    javascript推荐书籍
    [zt]介绍一本搜索引擎爬虫方面的好书
    一些文章资源和趣闻
    【详细的英语自学指导】黑猫出版社 Easyreads系列13本书,科普英语,入门好选择
    网上邻居疑难问题分析与总结
    关于文件夹权限的十个问答
    net send命令解析
    如何成为一名黑客
    全球最值得模仿的230个网站
    女生最爱不释手的30个网站
  • 原文地址:https://www.cnblogs.com/bhlsheji/p/4913092.html
Copyright © 2011-2022 走看看