C++设计模式之单例模式
来源:互联网 发布:sql语句建表 列名别名 编辑:程序博客网 时间:2024/06/07 18:50
在游戏开发过程中,我们时常会遇到单例模式的运用场景。比如你游戏当中的最终BOSS,你希望你的BOSS只能有一个,所以这里你就可以用单例模式;那么什么是单例模式呢?看下面的代码分析。
#include <cstdlib>#include <iostream>using namespace std;class Singleton{private: static Singleton* instance; Singleton() { } public: static Singleton* GetInstance() { if (instance == NULL) { instance = new Singleton; cout << "I am new!" << endl; } return instance; } void TestOut() { cout << "void TestOut()" << endl; }};Singleton* Singleton::instance = NULL;int main(int argc, char *argv[]){ //Singleton* s1 = new Singleton;//不能再new出对象了 Singleton* s2 = Singleton::GetInstance(); Singleton* s3 = Singleton::GetInstance(); Singleton::GetInstance()->TestOut(); cout << s2 << endl; cout << s3 << endl; system("PAUSE"); return EXIT_SUCCESS;}上面就实现了一个单例类,把构造函数私有之后,你就不能在new出新的对象,而且你每次获取到的对象都只有一个,所以这样我们游戏中的最终BOSS只能有一个。
0 0
- (C#)设计模式 之 单例模式
- 设计模式之单例模式(C++)
- C#--设计模式之单例模式
- Objective-C 设计模式之单例
- Objective-C之单例设计模式
- 设计模式之单例模式(C++)
- C语言和设计模式(之单例模式)
- Objective-C中的设计模式之单例模式
- 设计模式之 单例设计模式
- 设计模式之 单例设计模式
- 设计模式之单例设计模式
- 设计模式之-----------单例设计模式
- 设计模式之:单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 和小白一起学ABAP -- 7 阅读经典之SAP程序设计
- C#反射遍历/查询类中的属性以及值
- c语言练习 5-3. 求a的连续和
- 图片自适应浏览器
- 黑马程序员—java5的枚举
- C++设计模式之单例模式
- [转] Linux常用C函数-日期时间篇
- Android多任务下载,使用Notification更新进度条
- MFC单例运行三种方式
- 不想当业务员的培训经理不是好的CEO
- Grunt中批量无损压缩图片插件--Grunt-contrib-imagemin
- android4.0强制横屏竖屏
- Bulk copy failed user does not have alter table permission
- [转]Linux常用C函数-内存控制篇