單例模式的代碼重複率太高,所以我就用模板來實現,提高了代碼複用率
單例模式的實現要點:
1. 構造函數私有
2. 暴露一個函數來獲取實例
可以用模板實現保存和獲取實例,子類只要繼承模板類就可以了
這裏有個問題就是子類的構造函數是private的那麼父類也不能構造,所以還需要把父類聲明爲友元類,這裏用了宏來實現
#pragma once
template<class T>
class Singleton
{
protected:
Singleton() = default;
virtual ~Singleton() = default;
public:
static T& GetInstance()
{
static T s_instance;
return s_instance;
}
};
#define DECL_SINGLETON(T) friend class Singleton<T>
上面是把實例放在函數的靜態局部變量了,這樣是第一次調用GetInstance時初始化實例
另一種寫法是把實例放在類的靜態變量裏,這樣就和全局變量一樣是在main函數之前初始化。因爲要放到頭文件裏,所以要用Visual C++特有的關鍵字__declspec(selectany)
來避免重定義
#pragma once
template<class T>
class Singleton
{
protected:
Singleton() = default;
virtual ~Singleton() = default;
private:
static T s_instance;
public:
static T& GetInstance()
{
return s_instance;
}
};
template<class T>
__declspec(selectany) T Singleton<T>::s_instance;
#define DECL_SINGLETON(T) friend class Singleton<T>
使用方法:
class A final : public Singleton<A>
{
DECL_SINGLETON(A);
private:
A() = default;
virtual ~A() = default;
};