单例模式
单例模式 是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例的特殊类。通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问,从而方便对实例个数的控制并节约系统资源。如果希望系统中某个类的对象只能存在一个,单例模式是最好的解决方案。
如操作系统的任务管理器,只需要一个即可,下次打开还是你上次打开的任务管理器。因此需要控制单例对象的个数。
实现单例步骤
1、构造函数私有化
2、增加静态私有的当前类的指针变量
3、提供对外静态接口,可以让用户获得单例对象
单例模式分为懒汉式和饿汉式
#include<iostream>
using namespace std;
//单例模式分为懒汉式和饿汉式
//懒汉式
class Singleton_lazy
{
private:
Singleton_lazy(){cout<<"我是懒汉!"<<endl;}
public:
static Singleton_lazy* getInstance()
{
if(pSinleton == NULL){
pSinleton = new Singleton_lazy;
}
return pSinleton;
}
private:
static Singleton_lazy* pSinleton;
};
//类外初始化
Singleton_lazy* Singleton_lazy::pSinleton = NULL;//等需要时在进行构造,懒汉
//饿汉式
class Singleton_hungry
{
private:
Singleton_hungry(){cout<<"我是饿汉!"<<endl;}
public:
static Singleton_hungry* getInstance(){
return pSinleton;
}
//单例对象释放问题
//一般需要考虑,因为new的类放在堆上,占用不了多少内存
class Garbo{
~Garbo(){
if(pSinleton != NULL)
{
delete pSinleton;
}
}
};
private:
static Singleton_hungry* pSinleton;
static Garbo garbo;
};
//类外初始化
Singleton_hungry* Singleton_hungry::pSinleton = new Singleton_hungry;//在main函数执行之前就已经构造好了,饿汉
//测试上述两种是否是单例模式
void test01()
{
Singleton_lazy* p1 = Singleton_lazy::getInstance();
Singleton_lazy* p2 = Singleton_lazy::getInstance();
if(p1 == p2){
cout<<"两个指针指向同一块内存,是单例模式!"<<endl;
}else{
cout<<"不是单例模式!"<<endl;
}
Singleton_hungry* p3 = Singleton_hungry::getInstance();
Singleton_hungry* p4 = Singleton_hungry::getInstance();
if(p3 == p4){
cout<<"两个指针指向同一块内存,是单例模式!"<<endl;
}else{
cout<<"不是单例模式!"<<endl;
}
}
int main(void)
{
cout<<"main函数开始执行!"<<endl;
test01();
system("pause");
return 0;
}