设计模式《一》——单例模式

简介

单例对象(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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值