一、UML图
注意:唯一一个私有静态数据成员,构造函数和析构函数声明为私有或保护成员,一个公有的获取单例实例的静态方法。
二、Cocos2d-x中经常使用的单例模式代码
#include <iostream>
class Singleton
{
public:
static Singleton* getInstance();
void Func();
private:
Singleton();
~Singleton();
static Singleton* m_pInstance;
};
Singleton::Singleton()
{
std::cout << "this is constructor." << std::endl;
}
Singleton::~Singleton()
{
std::cout << "this is destructor." << std::endl;
}
// 静态实例初始化
Singleton* Singleton::m_pInstance = NULL; // nullptr
Singleton* Singleton::getInstance()
{
if (!m_pInstance){
m_pInstance = new Singleton();// 切记不能将这行代码写在if语句的前面;否则每次获得新的实例(如果有其他数据成员,也都是初始的值,即使修改了这些数据成员),而不是唯一的实例。
return m_pInstance;
}
return m_pInstance;
}
void Singleton::Func()
{
std::cout << "this is a function that Cocos2d-x often definates." << std::endl;
}
void main()
{
Singleton::getInstance()->Func();// Director* director = Director::getInstance()->getVisiableSize();
std::cin.get();
}
执行结果: