cocos2d中的设计模式

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过程。

相关文章

    本文实践自 RayWenderlich、Ali Hafizji 的文章《...
Cocos-code-ide使用入门学习地点:杭州滨江邮箱:appdevzw@1...
第一次開始用手游引擎挺激动!!!进入正题。下载资源1:从C...
    Cocos2d-x是一款强大的基于OpenGLES的跨平台游戏开发...
1.  来源 QuickV3sample项目中的2048样例游戏,以及最近《...
   Cocos2d-x3.x已经支持使用CMake来进行构建了,这里尝试...