Cocos2d-x常用设计模式——单例模式
2016-09-28 20:57
274 查看
一、UML图
![](http://img.blog.csdn.net/20160928205401529?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
注意:唯一一个私有静态数据成员,构造函数和析构函数声明为私有或保护成员,一个公有的获取单例实例的静态方法。
二、Cocos2d-x中经常使用的单例模式代码
注意:唯一一个私有静态数据成员,构造函数和析构函数声明为私有或保护成员,一个公有的获取单例实例的静态方法。
二、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(); }执行结果:
相关文章推荐
- Cocos2d-x常用设计模式——观察者模式
- 运行时看常用的几种设计模式——Design Patterns in Run-time View
- 架构师常用的五种 PHP 设计模式
- .NET常用设计模式——迭代器模式
- 游戏开发中常用的设计模式
- NET常用设计模式——代理(Proxy)模式
- 游戏开发中常用的设计模式
- Java常用的设计模式
- 激烈讨论:我最常用的设计模式
- 游戏开发中常用的设计模式
- 哪个设计模式最常用?
- j2ee常用的设计模式?说明工厂模式
- Tiny-OS Programming/八种常用设计模式
- NET常用设计模式——单件模式
- Bridge? 一个GIS二次开发中常用的设计模式
- Windows应用开发中常用的设计模式
- .NET常用设计模式——工厂模式
- 在web应用中常用的设计模式
- 在web应用中常用的设计模式
- Windows应用开发中常用的设计模式