2.单例模式

一、定义

确保一个类仅有一个唯一的实例,并且提供一个全局的访问点。

二、要解决的问题

  • 独生子女
    无论new了多少个对象,始终只存在一个实例
  • 应用场景
    对临界资源(例如日志、打印机)的访问

三、解决步骤

  1. 将构造函数声明成私有类型
  2. 声明一个类的静态实例
  3. 提供一个获得实例的方法

四、代码实现

4.1 实现方法1

下面这种方式存在以下问题

  • 只提供了getInstance方法获取对象,没有提供释放函数
  • 析构函数不会被运行
  • 多线程调用getInstance时将不是线程安全的
cpp 复制代码
class Singleton
{
private:
	static Singleton* singleton;  //实例对象为私有

	Singleton()  //构造方法为私有
	{
		std::cout << "Singleton" << std::endl;
	}
	
	~Singleton()
	{
		std::cout << "~Singleton" << std::endl;
	}

public:
	static Singleton& getInstance()
	{
		if (!singleton)
		{
			singleton = new Singleton();
		}

		return *singleton;
	}

	void printAddress()
	{
		printf("%p\n", this);
	}
};

Singleton* Singleton::singleton = nullptr;

4.2 实现方法2

改进点

  • 禁止单例模式的拷贝和赋值
  • 采用局部静态变量的方式返回,线程安全(c++11及以后)
  • 没有采用new关键字在堆空间中申请内存,空间被自动管理
  • 析构函数被自动执行
cpp 复制代码
class Singleton
{
private:
	Singleton()  //构造方法为私有
	{
		std::cout << "Singleton" << std::endl;
	}
	~Singleton()
	{
		std::cout << "~Singleton" << std::endl;
	}

	//禁止拷贝和赋值
	Singleton(const Singleton& obj) = delete;
	Singleton& operator=(const Singleton& obj) = delete;


public:
	static Singleton& getIntance()
	{
		static Singleton instance;

		return instance;
	}

	void printAddress()
	{
		printf("%p\n", this);
	}
};

int main()
{
	Singleton::getIntance().printAddress();
	Singleton::getIntance().printAddress();
}
相关推荐
o0向阳而生0o3 小时前
100、23种设计模式之适配器模式(9/23)
设计模式·适配器模式
将编程培养成爱好4 小时前
C++ 设计模式《外卖菜单展示》
c++·设计模式
赶飞机偏偏下雨5 小时前
【Java笔记】单例模式
java·笔记·单例模式
TechNomad12 小时前
设计模式:状态模式(State Pattern)
设计模式·状态模式
努力也学不会java12 小时前
【设计模式】 原型模式
java·设计模式·原型模式
TechNomad15 小时前
设计模式:模板方法模式(Template Method Pattern)
设计模式·模板方法模式
leo030817 小时前
7种流行Prompt设计模式详解:适用场景与最佳实践
设计模式·prompt
ytadpole19 小时前
揭秘设计模式:工厂模式的五级进化之路
java·设计模式
烛阴20 小时前
【TS 设计模式完全指南】用工厂方法模式打造你的“对象生产线”
javascript·设计模式·typescript
ArabySide21 小时前
【C#】 资源共享和实例管理:静态类,Lazy<T>单例模式,IOC容器Singleton我们该如何选
单例模式·c#·.net core