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