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

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值