1 概念
单例模式是一种对象创建型模式,使用单例模式,可以保证为一个类只生成唯一的实例对象。也就是说,在整个程序空间中,该类只存在一个实例对象。
GoF对单例模式的定义是:保证一个类、只有一个实例存在,同时提供能对该实例加以访问的全局访问方法。
2 为什么使用单例模式
在应用系统开发中,我们常常有以下需求:
- 在多个线程之间,比如初始化一次socket资源;比如servlet环境,共享同一个资源或者操作同一个对象
- 在整个程序空间使用全局变量,共享资源
- 大规模系统中,为了性能的考虑,需要节省对象的创建时间等等。
因为Singleton模式可以保证为一个类只生成唯一的实例对象,所以这些情况,Singleton模式就派上用场了。
3实现单例步骤常用步骤
a) 构造函数私有化
b) 提供一个全局的静态方法(全局访问点)
c) 在类中定义一个静态指针,指向本类的变量的静态变量指针
**饿汉式:**即静态初始化的方式,它是类一加载就实例化的对象(实例化对象 new放在main函数外面),所以要提前占用系统资源。
**懒汉式:**有需要的时候再实例化对象。
4 示例代码a:普通懒汉式(多线程不安全)
#include <iostream>
using namespace std;
//////////////////0 普通懒汉式 (多线程不安全)//////////////////////////
class Singelton
{
private:
Singelton() //将构造函数私有化
{
m_singer = NULL;
m_count = 0;
cout << "构造函数Singelton ... do" << endl;
}
public:
static Singelton *getInstance()
{
if (m_singer == NULL) //懒汉式:1 每次获取实例化对象都要判断 2 多线程会有问题,每个线程都会创建一次构造函数
{
m_singer = new Singelton;
}
return m_singer;
}
static void printT()
{
cout << "m_count: " << m_count << endl;
}
private:
static Singelton *m_singer;
static int m_count;
};
Singelton *Singelton::m_singer = NULL; //懒汉式 并没有创建单例对象
int Singelton::m_count = 0;
void main()
{
cout << "演示 懒汉式" << endl;
Singelton *p1 = Singelton::getInstance(); //只有在使用的时候,才去创建对象。
Singelton *p2 = Singelton::getInstance();
if (p1 != p2)
{
cout << "不是同一个对象" << endl;
}
else // p1与p2必然相等
{
cout << "是同一个对象" << endl;
}
p1->printT();
p2->printT();
system("pause");
return;
}
5 示例代码b:多线程安全的懒汉式
ToDo
6 示例代码c: 饿汉式(本身就线程安全)
#include <iostream>
using namespace std;
//饿汉式
class Singelton2
{
private:
Singelton2() // 将构造函数私有化
{
m_singer = NULL;
m_count = 0;
cout << "构造函数Singelton ... do" << endl;
}
public:
static Singelton2 *getInstance()
{
// if (m_singer == NULL )
// {
// m_singer = new Singelton2;
// }
return m_singer;
}
static void Singelton2::FreeInstance()
{
if (m_singer != NULL)
{
delete m_singer;
m_singer = NULL;
m_count = 0;
}
}
static void printT()
{
cout << "m_count: " << m_count << endl;
}
private:
static Singelton2 *m_singer;
static int m_count;
};
Singelton2 *Singelton2::m_singer = new Singelton2; //不管你创建不创建实例,均把实例new出来
int Singelton2::m_count = 0;
void main()
{
cout << "演示 饿汉式" << endl;
Singelton2 *p1 = Singelton2::getInstance(); //只有在使用的时候,才去创建对象。
Singelton2 *p2 = Singelton2::getInstance();
if (p1 != p2)
{
cout << "不是同一个对象" << endl;
}
else
{
cout << "是同一个对象" << endl;
}
p1->printT();
p2->printT();
Singelton2::FreeInstance();
Singelton2::FreeInstance();
system("pause");
}
来源:CSDN
作者:码就行了
链接:https://blog.csdn.net/weixin_45915902/article/details/104580720