【C++】62.单例类模板

 

在架构设计时,某些类在整个系统生命期中最多只能有一个对象存在(Single Instance)

如何定义一个类,使得这个类最多只创建一个对象?

思路

  1. 要控制类的对象数目,必需对外隐藏构造函数
  2. 将构造函数的访问属性设置为 private
  3. 定义 instance 并初始化为 NULL
  4. 当需要使用对象时,访问 instance 的值
  •            空值:创建对象,并用 instance 标记
  •            非空值: 返回 instance 标记的对象

class CSingleton
{ 
	static CSingleton *m_instance;
	CSingleton(const CSingleton&);
	CSingleton& operator = (const CSingleton&);
	CSingleton()
	{}
public:
	static CSingleton* getInstance();
	
	void print()
	{
		cout << "this = " << this << endl;
	}
		
};

CSingleton* CSingleton::m_instance = NULL;

CSingleton* CSingleton::getInstance()
{
	if( m_instance == NULL )
	{
		m_instance = new CSingleton();
	}
	
	return m_instance;	
}

int main()
{
	CSingleton* s = CSingleton::getInstance();
    CSingleton* s1 = CSingleton::getInstance();
    CSingleton* s2 = CSingleton::getInstance();
    
    s->print();
    s1->print();
    s2->print();

    
    return 0;
}
this = 0x1d1ec20
this = 0x1d1ec20
this = 0x1d1ec20

存在的问题

  • 需要使用单例模式时:
    1. 必须定义静态成员变量 m_instance
    2. 必须定义静态成员函数 getInstance()

解决方案

将单例模式相关的代码抽取出来,开发单例类模板,当需要的单例类的时候

直接使用单例类模板

#ifndef _SINGLETON_H_
#define _SINGLETON_H_

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

 

小结

  • 单例模式是开发中最常用的设计模式之一
  • 单例模式的应用使得一个类最多只有一个对象
  • 可以将单例模式相关的代码抽象成类模板

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值