为什么使用单例模式
在应用系统开发中,我们常常有以下需求:
- 在多个线程之间,比如初始化一次socket资源;比如servlet环境,共享同一个资源或者操作同一个对象
- 在整个程序空间使用全局变量,共享资源
- 大规模系统中,为了性能的考虑,需要节省对象的创建时间等等。
因为Singleton模式可以保证为一个类只生成唯一的实例对象,所以这些情况,Singleton模式就派上用场了。
2.2.3实现单例步骤常用步骤
a)构造函数私有化
b)提供一个全局的静态方法(全局访问点)
c)在类中定义一个静态指针,指向本类的变量的静态变量指针
#include <iostream>
using namespace std;
//懒汉式
class Singelton
{
private:
Singelton()
{
cout << "Singelton 构造函数执行" << endl;
}
public:
static Singelton *getInstance()
{
if (m_psl == NULL)
{
m_psl = new Singelton;
}
return m_psl;
}
static void FreeInstance()
{
if (m_psl != NULL)
{
delete m_psl;
m_psl = NULL;
}
}
private:
static Singelton *m_psl;
};
Singelton *Singelton::m_psl = NULL;
void fun()
{
Singelton *p1 = Singelton::getInstance();
Singelton *p2 = Singelton::getInstance();
if (p1 == p2)
{
cout << "是同一个对象" << endl;
}
else
{
cout << "不是同一个对象" << endl;
}
Singelton::FreeInstance();
}
int main()
{
fun();
system("pause");
return 0;
}
#include <iostream>
using namespace std;
//饿汉式
class Singelton
{
private:
Singelton()
{
cout << "Singelton 构造函数执行" << endl;
}
public:
static Singelton *getInstance()
{
return m_psl;
}
static void FreeInstance()
{
if (m_psl != NULL)
{
delete m_psl;
m_psl = NULL;
}
}
private:
static Singelton *m_psl;
};
Singelton *Singelton::m_psl = new Singelton;
void fun()
{
Singelton *p1 = Singelton::getInstance();
Singelton *p2 = Singelton::getInstance();
if (p1 == p2)
{
cout << "是同一个对象" << endl;
}
else
{
cout << "不是同一个对象" << endl;
}
Singelton::FreeInstance();
}
int main()
{
fun();
system("pause");
return 0;
}
---------------------
本文来自 小麦大大 的优快云 博客 ,全文地址请点击:https://blog.youkuaiyun.com/qq_35433716/article/details/82825835?utm_source=copy