加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

cocos2d中的设计模式

发布时间:2020-12-14 19:04:32 所属栏目:百科 来源:网络整理
导读:1.单例模式 其实就是静态全局对象,实现上一个静态成员变量,一个静态成员函数,构造函数私有化,和静态全局变量的区别是实例化的时机是可控制的。 2.委托模式 class SceneBDelegator { public: virtual ~SceneBDelegator() {} //回调委托对象 virtual void

1.单例模式

其实就是静态全局对象,实现上一个静态成员变量,一个静态成员函数,构造函数私有化,和静态全局变量的区别是实例化的时机是可控制的。

2.委托模式

class SceneBDelegator
{
public:
virtual ~SceneBDelegator() {}
//回调委托对象
virtual void callBack(void *ctx,const char *str) = 0;

};

class BLayer : public cocos2d::Layer
{
SceneBDelegator* _delegator;
public:


static cocos2d::Scene* createScene();
virtual bool init();


// 更新单例对象状态.
void menUpdate(cocos2d::Ref* pSender);


// 返回上一个场景.
void menReturnPreviousScene(cocos2d::Ref* pSender);

void setDelegator(SceneBDelegator* delegator);


// implement the "static create()" method manually
CREATE_FUNC(BLayer);


};

class ALayer : public cocos2d::Layer,public SceneBDelegator
{
public:
// there's no 'id' in cpp,so we recommend returning the class instance Vec2er
static cocos2d::Scene* createScene();


// Here's a difference. Method 'init' in cocos2d-x returns bool,instead of returning 'id' in cocos2d-iphone
virtual bool init();

// 进入下一个场景.
void menEnterNextScene(cocos2d::Ref* pSender);

virtual void callBack(void *ctx,const char *str);

// implement the "static create()" method manually
CREATE_FUNC(ALayer);
};

void ALayer::menEnterNextScene(Ref* pSender)
{
auto sc = Scene::create();
auto layer = BLayer::create();
layer->setDelegator(this);//ALayer继承SceneBDelegator的接口virtual void callBack(void *ctx,const char *str) = 0;
sc->addChild(layer);


auto reScene = TransitionSlideInR::create(1.0f,sc);
Director::getInstance()->pushScene(reScene);
}

void ALayer::callBack(void *ctx,const char *str)//实现
{
log("ALayer callBack");
Label* label = (Label*)this->getChildByTag(100);
if (label)
label->setString(str);
}

void BLayer::setDelegator(SceneBDelegator* delegator)//参数
{
_delegator = delegator;
}

void BLayer::menUpdate(Ref* pSender)
{
int num = CCRANDOM_0_1() * 1000;
__String* s = __String::createWithFormat("SceneA Update %d",num);
//回调HelloWorld场景
_delegator->callBack(this,s->getCString());//
log("%s",s->getCString());
}

3.观察者模式

注册通知

__NotificationCenter::getInstance()->addObserver(this,callfuncO_selector(ALayer::callBack),MSG_STATE,NULL);

解除通知

__NotificationCenter::getInstance()->removeObserver(this,MSG_STATE);

投送通知

__NotificationCenter::getInstance()->postNotification(MSG_STATE,s);

通知回调函数

void ALayer::callBack(cocos2d::Ref *sender)
{
log("ALayer callBack");
__String *str = (__String*)sender;
Label* label = (Label*)this->getChildByTag(100);
if (label)
label->setString(str->getCString());
}

4.工厂模式

工厂模式其实就是用一个工厂类封装new过程。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读