简介
单例对象(Singleton)是一种常用的设计模式。其保障一个类只有单个对象被创建,在Java应用中,单例对象能保证在一个JVM中,该对象只有一个实例存在。这样的模式有几个好处:
1、某些类创建比较频繁,对于一些大型的对象,这是一笔很大的系统开销。
2、省去了new操作符,降低了系统内存的使用频率,减轻GC压力。
3、有些类如交易所的核心交易引擎,控制着交易流程,如果该类可以创建多个的话,系统完全乱了。(比如一个军队出现了多个司令员同时指挥,肯定会乱成一团),所以只有使用单例模式,才能保证核心交易服务器独立控制整个流程
实现
#include <iostream>
#include <mutex>
#if 1
// 懒汉式;即只有使用到的时候才去实例化,线程不安全,如多个线程同时执行时,并且
// 构造函数需要执行时间,就会导致多次执行构造函数,构造函数不安全,违背单例原则。
// 可以通过锁机制解决多线程安全问题。
class Singleton{
private:
Singleton() { }
static Singleton * pInstance;
public:
static Singleton * GetInstance(){
if (pInstance == nullptr)
pInstance = new Singleton();
return pInstance;
}
static void FreeInstance() {
if (pInstance != NULL) {
delete pInstance;
pInstance = NULL;
}
}
};
// 线程安全懒汉式版本。
class Singleton {
private:
Singleton() { }
static Singleton * pInstance;
static std::mutex mux;
public:
static Singleton * GetInstance() {
if (pInstance == nullptr) {
std::lock_guard<std::mutex> lock{mux};
pInstance = new Singleton();
}
return pInstance;
}
static void FreeInstance() {
if (pInstance != NULL) {
delete pInstance;
pInstance = NULL;
}
}
};
#endif
// 线程安全的单例模式
class Singleton{
private:
Singleton() { }
~Singleton() { }
Singleton(const Singleton &);
Singleton & operator = (const Singleton &);
public:
static Singleton & GetInstance(){
static Singleton instance;
return instance;
}
void print() {
std::cout << "hello world" << std::endl;
}
};
int main(int argc, char* argv[]) {
Singleton& single = Singleton::GetInstance();
single.print();
std::cin.get();
return 0;
}