单例模式一(Singleton)
来源:互联网 发布:淘宝新规则2017及处罚 编辑:程序博客网 时间:2024/06/11 16:39
定义
顾名思义,当类A在程序中只有唯一的一个实例,在程序中的其他地方试图对类A进行操作的时候都只能是通过这个实例进行,那么这类A就可以说是应用了单例模式。
一般用法
对于单例模式,一般可以如以下代码实现:
在 .h 文件中:
class Singleton{public: Singleton(){} ~Singleton(){} static Singleton* getInstance(); static void destoryInstance();}
在.cpp文件中:
static Singleton* g_pInstance = NULL;Singleton* Singleton::getInstance(){ if(NULL == g_pInstance){ g_pInstance = new Singleton(); } return g_pInstance;}void Singleton::destoryInstance(){ if(g_pInstance){ delete g_pInstance; g_pInstance = NULL; }}
如上面代码所示,由于static Singleton* g_pInstance = NULL;
被定义在cpp文件中的,所以如果在类外想访问g_pInstance 的话,就只能通过Singleton的getInstance()方法获取。这样,貌似是达到了单例的原则了。
改进
再看Singleton的头文件,我们发现,在Singleton的构造函数定义是public,这意味着,如果我们在程序中直接new 一个Singleton出来是完全可以的,一旦在程序中我们new了一个Singleton,那么我们的Singleton就变得不是唯一了。为了避免这种情况发生,我们需要将Singleton的构造函数设置成private, 从而禁止Singleton被new创建。如下:
class Singleton{ private: Singleton(); ~Singleton(); public: static Singleton* getInstance(); staic void destoryInstance();}
改进后的Singleton类将再不能被new创建,所以要使用Singleton类就只能乖乖调用类中的getInstance()函数。而调用这个函数时,返回的是g_pInstance这个静态全局变量,这个变量只能在定义的这个文件中被使用,从而实现了单例。
总结
在对某个类实现单例模式的过程中,要注意确保:除了调用类自身提供的函数以外,再没有办法可以获取到类的实例。如在C++中,很易会漏掉将构造函数private化,导致获取实例的方法不唯一。
0 0
- 单例模式一(Singleton)
- 设计模式 一 单例模式Singleton
- 单例(Singleton)模式
- singleton 单例模式
- Singleton单例模式
- Singleton(单例)模式
- Singleton 单例模式
- 单例模式(Singleton)
- 单例模式(Singleton)
- Singleton(单例)模式
- Singleton(单例)模式
- 单例模式(Singleton)
- 单例模式(Singleton)
- 单例模式Singleton
- Singleton (单例模式)
- Singleton单例模式
- 单例模式----SingleTon
- 单例模式-singleton
- 圆形进度条的绘制与使用
- POJ 1947 Rebuilding Roads (树形dp 经典题)
- VPN
- sift笔记
- Java学习之任务调度--Timer
- 单例模式一(Singleton)
- 机器学习处理图片数据并识别图片情感
- C语言深入学习系列
- ecshop模板标签
- android LinearLayout代码方式实现Weight
- C,C++宏中#与##的讲解
- 本地化UIImagePicker中的文字
- hdu 5184 卡特兰数
- 对于获取浏览器页面大小的问题