Cocos2d-x常用设计模式—单例模式

发表于2017-12-21
评论0 1.5k浏览
Cocos2d-x作为一款常用的开源游戏框架,使用范围就不多说了,下面就给大家介绍Cocos2d-x中常会使用到的单例模式,如果有不了解的可以看看。


一、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();  
} 


执行结果:

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引