设计模式 -- 单例模式(Singleton)
2015-11-13 10:45
477 查看
单例模式
Singleton模式解决问题十分常见而且比较简单。那么什么是单例模式呢?其实就是创建一个唯一的类对象,内存中只占有一份。那么问题来了,要怎么创建一个唯一对象呢?当然,直接定义一个全局的对象可以实现,但在有些纯粹的面向对象语言中,如C#,jave中,就不能定义全局变量了。那么,除了全局变量还有什么是唯一性的呢?恩,没错,就是static静态变量。我们的单例模式就是通过一个静态的类成员函数实现的(创建对象)。单例模式类对象是一个共享对象,内存中只有一份,节约了内存。它常常和工厂模式一起使用,因为工厂对象只需唯一一个就够了。
结构示意图:(一个static方法 + 一个对象指针)
示例代码
#ifndef __DesignMode__Singleton__ #define __DesignMode__Singleton__ #include <iostream> using namespace std; class Singleton { public: static Singleton * Instance(); protected: Singleton(); private: static Singleton* _instance; }; #endif /* defined(__DesignMode__Singleton__) */
#include "Singleton.h" #include <iostream> using namespace std; Singleton* Singleton::_instance = 0; Singleton::Singleton() { cout << "Singleton create ..." << endl; } Singleton* Singleton::Instance() { if (_instance == 0) { _instance = new Singleton(); } return _instance; }
#include "Singleton.h" #include <iostream> using namespace std; int main(int argc,char* argv[]) { Singleton* sgn1 = Singleton::Instance(); Singleton* sgn2 = Singleton::Instance(); Singleton* sgn3 = Singleton::Instance(); return 0; }
相关文章推荐
- 数据库设计の表分区
- linux:SUID、SGID详解
- 理解JavaScript的作用域链
- insert into,update,delete
- 设计模式-适配器模式
- Silverlight DevExpress ChartControl LineSeries2D效果展示
- HBuilder 快捷键
- 手机管理应用研究【3】—— 垃圾清理篇
- Java中volatile的作用以及用法
- ci Controller.php解析
- 错误处理:The hierarchy of the type MyMethodBeforeAdvice is inconsistent
- [Shell]使用find命令查找最近修改过的文件
- Github上iOS开源项目分类及
- JavaScript中的this
- android自定义CheckBox和RadioButton中文字和图片之间距离问题解决
- 微软华裔科学家和他们的又一次冲动
- Oracle 常见问题整理,来自CSDN帖子
- Kettle 连接 oracle
- SAP Press Accelerated Financial Closing with SAP PDF 电子版
- Struts2系统学习(7)Action中取得请求参数的方法总结