cocos2d-x 的单例大部分出现在一些系统的资源管理类之中,单例模式保证了全局有且只有一个实例对象,保证了自动地初始化该对象,使得程序在任何时候任何地方都可以访问、获取这个对象。
cocos2d-x CCDirector的代码片段:
<span style="font-size:14px;">static DisplayLinkDirector *s_SharedDirector = nullptr;
Director* Director::getInstance()
{
if (!s_SharedDirector)
{
s_SharedDirector = new DisplayLinkDirector();
s_SharedDirector->init();
}
return s_SharedDirector;
}</span>
cocos2d-x 的游戏流程控制器CCDirector是一个独一无二的控制器,用于切换游戏场景。一个游戏中只会存在一个CCDirector实例。
单例模式
<span style="font-size:14px;">#ifndef _GLOBAL_H_
#define _GLOBAL_H_
#include "iostream"
class Global{
public:
int m_nGlobal; //存储着全局唯一可以访问的变量
static Global* GetGlobal(); //通过这个方法返回Global对象
protected:
~Global();
};
#endif</span>
<span style="font-size:14px;">#include "Global.h"
static Global* shared = nullptr;
Global::~Global()
{
}
Global* Global::GetGlobal()
{
if(!shared)
{
shared = new Global();
std::cout << "first" ;
}
std::cout << "object exist";
return shared;
}</span>
第二种方式
<span style="font-size:14px;">#ifndef _GLOBAL_H_
#define _GLOBAL_H_
#include "iostream"
class Global{
public:
int m_nGlobal; //存储着全局唯一可以访问的变量
static Global* shared; //对象的声明
static Global* GetGlobal(); //通过这个方法返回Global对象
protected:
~Global();
};
#endif</span>
<span style="font-size:14px;">#include "Global.h"
Global* Global::shared = nullptr; //初始化
Global::~Global()
{
}
Global* Global::GetGlobal()
{
if(!shared)
{
shared = new Global();
std::cout << "first" ;
}
std::cout << "object exist";
return shared;
}</span>
第二种初始化方式要注意初始化位置。