单例模式:
- 一个类只允许创建唯一的对象
- 禁止在类的外部创建对象:私有化构造函数:private或protected
- 类的内部维护唯一对象:静态成员变量
- 提供访问单例对象的方法:静态成员函数,返回在类内部唯一构造的实例
创建方式:
--》饿汉式:单例对象无论用或不用,程序启动即创建。
--》懒汉式:单例对象在用的时候再创建,不用即销毁。
实现:
一:
#include <iostream>
using namespace std;
class Singleton
{
public:
static Singleton *GetInstance()
{
if (m_Instance == NULL )
{
m_Instance = new Singleton ();
}
return m_Instance;
}
static void DestoryInstance()
{
if (m_Instance != NULL )
{
delete m_Instance;
m_Instance = NULL ;
}
}
// This is just a operation example
int GetTest()
{
return m_Test;
}
private:
Singleton()
{
m_Test = 10;
}
static Singleton *m_Instance;
int m_Test;
};
Singleton *Singleton ::m_Instance = NULL;
int main()
{
Singleton *singletonObj = Singleton ::GetInstance();
cout<<singletonObj->GetTest()<<endl;
Singleton ::DestoryInstance();
return 0;
}
二:多线程下单例模式实现
#include <iostream>
using namespace std;
class Singleton
{
public:
static Singleton *GetInstance()
{
if (m_Instance == NULL )
{
Lock(); // C++没有直接的Lock操作,请使用其它库的Lock,比如Boost,此处仅为了说明
if (m_Instance == NULL )
{
m_Instance = new Singleton ();
}
UnLock(); // C++没有直接的Lock操作,请使用其它库的Lock,比如Boost,此处仅为了说明
}
return m_Instance;
}
static void DestoryInstance()
{
if (m_Instance != NULL )
{
delete m_Instance;
m_Instance = NULL ;
}
}
int GetTest()
{
return m_Test;
}
private:
Singleton(){ m_Test = 0; }
static Singleton *m_Instance;
int m_Test;
};
Singleton *Singleton ::m_Instance = NULL;
int main()
{
Singleton *singletonObj = Singleton ::GetInstance();
cout<<singletonObj->GetTest()<<endl;
Singleton ::DestoryInstance();
return 0;
}
为何要使用双重检查锁定呢?上文已经大概说了一下。
考虑这样一种情况,就是有两个线程同时到达,即同时调用 GetInstance() 方法,
此时由于 m_Instance == null ,所以很明显,两个线程都可以通过第一重的 m_Instance == null ,
进入第一重 if 语句后,由于存在锁机制,所以会有一个线程进入 lock 语句并进入第二重 m_Instance == null ,
而另外的一个线程则会在 lock 语句的外面等待。
而当第一个线程执行完 new Singleton ()语句后,便会退出锁定区域,此时,第二个线程便可以进入 lock 语句块,
此时,如果没有第二重 m_Instance == null 的话,那么第二个线程还是可以调用 new Singleton ()语句,
这样第二个线程也会创建一个 SingleTon实例,这样也还是违背了单例模式的初衷的,
所以这里必须要使用双重检查锁定。
细心的朋友一定会发现,如果我去掉第一重 m_Instance == null ,程序还是可以在多线程下完好的运行的,
考虑在没有第一重 m_Instance == null 的情况下,
当有两个线程同时到达,此时,由于 lock 机制的存在,第一个线程会进入 lock 语句块,并且可以顺利执行 new SingleTon(),
当第一个线程退出 lock 语句块时, singleTon 这个静态变量已不为 null 了,所以当第二个线程进入 lock 时,
还是会被第二重 m_Instance == null 挡在外面,而无法执行 new Singleton(),
所以在没有第一重 m_Instance == null 的情况下,也是可以实现单例模式的?那么为什么需要第一重 singleton == null 呢?
这里就涉及一个性能问题了,因为对于单例模式的话,new SingleTon()只需要执行一次就 OK 了,
而如果没有第一重 m_Instance == null 的话,每一次有线程进入GetInstance()时,均会执行锁定操作来实现线程同步,
这是非常耗费性能的,而如果我加上第一重 m_Instance == null 的话,
那么就只有在第一次,也就是 m_Instance ==null 成立时的情况下执行一次锁定以实现线程同步,
而以后的话,便只要直接返回 Singleton 实例就 OK 了而根本无需再进入 lock 语句块了,这样就可以解决由线程同步带来的性能问题了。
但是,如果进行大数据的操作,加锁操作将成为一个性能的瓶颈;为此,一种新的单例模式的实现也就出现了。
三:
#include <iostream>
using namespace std;
class Singleton
{
public:
static Singleton *GetInstance()
{
return const_cast <Singleton *>(m_Instance);//const_cast参考链接:http://www.cnblogs.com/tianzeng/p/9062074.html
}
static void DestoryInstance()
{
if (m_Instance != NULL )
{
delete m_Instance;
m_Instance = NULL ;
}
}
int GetTest()
{
return m_Test;
}
private:
Singleton(){ m_Test = 10; }
static const Singleton *m_Instance;
int m_Test;
};
const Singleton *Singleton ::m_Instance = new Singleton();
int main()
{
Singleton *singletonObj = Singleton ::GetInstance();
cout<<singletonObj->GetTest()<<endl;
Singleton ::DestoryInstance();
}
因为静态初始化在程序开始时,也就是进入主函数之前,由主线程以单线程方式完成了初始化,所以静态初始化实例保证了线程安全性。在性能要求比较高时,
就可以使用这种方式,从而避免频繁的加锁和解锁造成的资源浪费。由于上述三种实现,都要考虑到实例的销毁,关于实例的销毁,待会在分析。由此,就出现了第四种实现方式:
四:
#include <iostream>
using namespace std;
class Singleton
{
public:
static Singleton *GetInstance()
{
static Singleton m_Instance;
return &m_Instance;
}
int GetTest()
{
return m_Test++;
}
private:
Singleton(){ m_Test = 10; };
int m_Test;
};
int main(int argc , char *argv [])
{
Singleton *singletonObj = Singleton ::GetInstance();
cout<<singletonObj->GetTest()<<"----->"<<Singleton::GetInstance()<<endl;;
singletonObj = Singleton ::GetInstance();
cout<<singletonObj->GetTest()<<"----->"<<Singleton::GetInstance()<<endl;
}
实例销毁
在上述的四种方法中,除了第四种没有使用new操作符实例化对象以外,其余三种都使用了;我们一般的编程观念是,new操作是需要和delete操作进行匹配的;是的,这种观念是正确的。在上述的实现中,是添加了一个DestoryInstance的static函数,这也是最简单,最普通的处理方法了;但是,很多时候,我们是很容易忘记调用DestoryInstance函数,就像你忘记了调用delete操作一样。由于怕忘记delete操作,所以就有了智能指针;那么,在单例模型中,没有“智能单例”,该怎么办?怎么办?
那我先从实际的项目中说起吧,在实际项目中,特别是客户端开发,其实是不在乎这个实例的销毁的。因为,全局就这么一个变量,全局都要用,它的生命周期伴随着软件的生命周期,软件结束了,它也就自然而然的结束了,因为一个程序关闭之后,它会释放它占用的内存资源的,所以,也就没有所谓的内存泄漏了。但是,有以下情况,是必须需要进行实例销毁的:
1.在类中,有一些文件锁了,文件句柄,数据库连接等等,这些随着程序的关闭而不会立即关闭的资源,必须要在程序关闭前,进行手动释放;
2.具有强迫症的程序员。
虽然,在代码实现部分的第四种方法能满足第二个条件,但是无法满足第一个条件。好了,接下来,就介绍一种方法,这种方法也是我从网上学习而来的,代码实现如下:
#include <iostream>
using namespace std;
class Singleton
{
public:
static Singleton *GetInstance()
{
return m_Instance;
}
int GetTest()
{
return m_Test;
}
private:
Singleton(){ m_Test = 10; }
static Singleton *m_Instance;
int m_Test;
// This is important
class GC
{
public :
~GC()
{
// We can destory all the resouce here, eg:db connector, file handle and so on
if (m_Instance != NULL )
{
cout<< "Here is the test" <<endl;
delete m_Instance;
m_Instance = NULL ;
}
}
};
static GC gc;
};
Singleton *Singleton ::m_Instance = new Singleton();
Singleton ::GC Singleton ::gc;
int main()
{
Singleton *singletonObj = Singleton ::GetInstance();
cout<<singletonObj->GetTest()<<endl;
return 0;
}
模式扩展
在实际项目中,一个模式不会像我们这里的代码那样简单,只有在熟练了各种设计模式的特点,才能更好的在实际项目中进行运用。单例模式和工厂模式在实际项目中经常见到,两种模式的组合,在项目中也是很常见的。所以,有必要总结一下两种模式的结合使用。
一种产品,在一个工厂中进行生产,这是一个工厂模式的描述;而只需要一个工厂,就可以生产一种产品,这是一个单例模式的描述。所以,在实际中,一种产品,我们只需要一个工厂,此时,就需要工厂模式和单例模式的结合设计。由于单例模式提供对外一个全局的访问点,所以,我们就需要使用简单工厂模式中那样的方法,定义一个标识,用来标识要创建的是哪一个单件。
参考:http://www.jb51.net/article/55863.htm