62、单例类模板

1、单例模式

  • 需求的提出
    在架构设计时,某些类在整个系统生命期中最多只能有一个对象存在(Single Instance)。
    提出问题:如何定义一个类,使得这个类最多只能创建一个对象?

解析:

  • 要控制类的数目,必须对外隐藏构造函数
  • 思路
    — 将构造函数的访问属性设置为 private
    — 定义 instance(标识符) 并初始化为 NULL
    — 当需要使用对象时,访问 instance 的值
       1、空值:创建对象,并用 instance 标记
       2、非空值:返回 instance 标记的对象
#include <iostream>
#include <string>

using namespace std;
class Test
{
	static Test* c_instance;
	Test()
	{

	}
	Test(const Test& obj);
	Test& operator = (const Test& obj);
	
public:
	static Test* GetInstance()
	{
		if (c_instance == NULL)
		{
			c_instance = new Test();
		}
		return c_instance;
	}
	void print()
	{
		cout << "this = " << this << endl;
	}
};

Test* Test::c_instance = NULL;

int main()
{
	Test* a1 = Test::GetInstance();
	Test* a2 = Test::GetInstance();
	Test* a3 = Test::GetInstance();

	a1->print();
	a2->print();
	a3->print();
	return 0;
}

在这里插入图片描述
分析:
从结果我们可以看出,定义不同的指针都指向一个对象,这就是单例模式的效果。单例模式的对象不用 delete。

2、单例类模板

  • 单例模式存在的问题
    — 需要使用单例模式时:
       1、必须定义静态变量 c_instance
       2、必须定义静态成员函数 GetInstance
       
    所以我们有改进的地方,把它定义成一个单例类模板:
  • 解决方案:将单例模式相关的代码抽取出去,开发单例类模板。当需要单例类模板时,直接使用单例类模板。

Singleton.h

#ifndef _SINGLETON_H_
#define _SINGLETON_H_
#pragma once
template <typename T>
class singleton
{
	static T* c_instance;
public:
	static T* GetInstance();

};
template <typename T>
T* singleton<T>::c_instance = NULL;

template <typename T>
T* singleton<T>::GetInstance()
{
	if (c_instance == NULL)
	{
		c_instance = new T();
	}
	return c_instance;
}
#endif

main.cpp

#include <iostream>
#include <string>
#include "Singleton.h"
using namespace std;
class Test
{
	friend class singleton<Test>;		//当前类需要使用单例模式
	Test()
	{

	}
	Test(const Test& obj);
	Test& operator = (const Test& obj);
public:
	void print()
	{
		cout << "this = " << this << endl;
	}
};

int main()
{
	Test *ts1 = singleton<Test>::GetInstance();
	Test *ts2 = singleton<Test>::GetInstance();
	Test *ts3 = singleton<Test>::GetInstance();

	ts1->print();
	ts2->print();
	ts3->print();
	return 0;
}

在这里插入图片描述

小结:

  • 单例模式是开发中最常用的设计模式之一
  • 单例模式的应用使得一个类最多只有一个对象
  • 可以将单例模式相关的代码抽象成类模板
  • 需要使用单例模式的类直接使用单例模板
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值