单例模式
保证一个类仅有一个实例,并提供一个访问它的全局访问方法.
实例
main.cc:
#include "singleton.h"
#include <iostream>
#include <windows.h>
#include <stdio.h>
using namespace std;
int main(){
//this will cause compile error,because singleton construct is protected!
//Singleton *singleton = new singleton();
Singleton *singleton_p1 = Singleton::GetInstance();
Singleton *singleton_p2 = Singleton::GetInstance();
printf("singleton_p1:%p\nsingleton_p2:%p\nsingletons are the same!\n",singleton_p1,singleton_p2);
//clear
delete singleton_p1;
system("Pause");
return 0;
}
Singleton:
//singleton.h
#ifndef HELENDP_SOURCE_SINGLETON_H_
#define HELENDP_SOURCE_SINGLETON_H_
class Singleton{
public:
~Singleton();
static Singleton* GetInstance();
protected:
Singleton();
private:
static Singleton *singleton_;
};
#endif
//singleton.cc:
#include "singleton.h"
#include <iostream>
using namespace std;
#include <stdio.h>
//static member need to define for allocated memory , otherwise will cause compile error!
Singleton * Singleton::singleton_ = NULL;
Singleton::Singleton(){
cout << "Singleton construct!" << endl;
}
Singleton::~Singleton(){
cout << "Singleton destruct!" << endl;
}
Singleton* Singleton::GetInstance(){
if(NULL == singleton_){
singleton_ = new Singleton();
}
return singleton_;
}
代码和UML图(EA)工程文件,最后会整理打包上传.
UML类图
结构
- Singleton:单例类.
优点:
- 提供了对唯一实例的受控访问。因为单例类封装了它的唯一实例,所以它可以严格控制客户怎样以及何时访问它,并为设计及开发团队提供了共享的概念。
- 由于在系统内存中只存在一个对象,因此可以节约系统资源,对于一些需要频繁创建和销毁的对象,单例模式无疑可以提高系统的性能。
- 允许可变数目的实例。我们可以基于单例模式进行扩展,使用与单例控制相似的方法来获得指定个数的对象实例。
缺点:
- 由于单例模式中没有抽象层,因此单例类的扩展有很大的困难。
- 单例类的职责过重,在一定程度上违背了“单一职责原则”。因为单例类既充当了工厂角色,提供了工厂方法,同时又充当了产品角色,包含一些业务方法,将产品的创建和产品的本身的功能融合到一起。
- 滥用单例将带来一些负面问题,如为了节省资源将数据库连接池对象设计为单例类,可能会导致共享连接池对象的程序过多而出现连接池溢出;现在很多面向对象语言(如Java、C#)的运行环境都提供了自动垃圾回收的技术,因此,如果实例化的对象长时间不被利用,系统会认为它是垃圾,会自动销毁并回收资源,下次利用时又将重新实例化,这将导致对象状态的丢失。