【设计模式】 单例模式singleton

什么是单例模式?

The singleton design pattern ensures that a class has only one instance and provides a global point of access to that intance.

Encapsulated “just-in-time initialization" or “initialization on first use” or “lazy intialization”

应用场景

-Say each country can have only one president.
-configuration manager
-database manager

如何实现?

  1. make the constructor private
  2. create a private static variable named instance
  3. create a public static method as a global point of access to the instance.

C++ 代码实现

Singleton.h

class Singleton{

private:
	int data;
	static Singleton* instance;
	Singleton(int v = 0){ data = v;};
public:
	void setData(int val);
	int getData();
	static Singleton* getInstance();
};

Singleton.cpp

Singleton::instance = nullptr; //懒汉模式
//Singleton::instance = new Singleton(); //饿汉模式

void Singleton::setData(int val)
{
	data = val;
}

int Singleton::getData()
{
	return data;
}

Singleton* Singleton::getInstance()
{
	if(instance == nullptr)
		instance = new Singleton();//lazy intialization
	
	return instance;
}

main.cpp

int main()
{
	Singleton* singleton = Singleton::getInstance();
}

懒汉模式 vs 饿汉模式

懒汉模式: 效率高, but not thread safe(需要加锁)
饿汉模式: 效率低, but thread safe

Thread-safe Singleton with C++ 11 using Magic Statics
在C++11内部静态变量的方式里是线程安全的

class CSingleton final
{
public:
    static CSingleton& GetInstance();
 
private:
    CSingleton() = default;
    ~CSingleton() = default;
 
    CSingleton(const CSingleton&) = delete;
    CSingleton& operator=(const CSingleton&) = delete;
    CSingleton(CSingleton&&) = delete;
    CSingleton& operator=(CSingleton&&) = delete;
};
 
CSingleton& CSingleton::GetInstance()
{
    static CSingleton instance;
    return instance;
}

缺点(反模式)

Singleton is also considered as an “Anti-Pattern”.

  1. Singleton doesn’t support object-oriented design principles. It cannot be inherited. No control over creation. Prevents dependency injection.
  2. Singleton do not allow for TDD
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值