設計模式的核心價值是可 reuse。我們在開發中多少都碰過設計模式,只是有時「相交卻未相識」。本文談單例模式,並附帶一個實用的 C++ 技巧:用確定性析構自動釋放單例。
逐項落實的做法:
C++ 有「確定性析構」的特性:只要建立了物件,系統就一定會呼叫它的解構子。於是我們可以在單例類別中嵌套一個專用的內部類別,並宣告一個靜態成員物件;當程式結束、這個靜態物件被解構時,就在它的解構子裡 delete 掉單例實例。
這個做法的四個特徵:
# include <iostream>
using namespace std;
// 當 static Garbo garbo_ 的生命週期結束時,會呼叫嵌套類 Garbo 的解構子,
// 裡面再 delete instance_,這正是利用了物件確定性析構的原則
class Singleton
{
public:
static Singleton* GetInstance()
{
if (NULL == instance_) {
instance_ = new Singleton;
}
return instance_;
}
~Singleton()
{
cout << "~Singleton ..." << endl;
}
// 嵌套類:專責釋放
class Garbo
{
public:
~Garbo()
{
if (Singleton::instance_ != NULL) {
delete Singleton::instance_;
Singleton::instance_ = NULL; // 避免重複 delete
}
}
};
private:
// 禁止複製:只宣告不實作
Singleton(const Singleton& other);
Singleton& operator=(const Singleton& other);
Singleton()
{
cout << "Singleton ..." << endl;
}
static Singleton* instance_; // 僅宣告,需類外定義
static Garbo garbo_; // 僅宣告,需類外定義
};
// Garbo 是嵌套類,定義時前面要加 Singleton::
Singleton::Garbo Singleton::garbo_;
Singleton* Singleton::instance_ = NULL;
int main(void)
{
// 不管呼叫幾次,都會得到同一個實例
Singleton* s = Singleton::GetInstance();
Singleton* s1 = Singleton::GetInstance();
// Singleton s3(*s); → error:禁止複製
// Singleton s3 = *s; → error:禁止賦值
return 0; // 程式結束時自動釋放,不需呼叫任何 Free()
}
static Singleton inst; return &inst;,由語言保證執行緒安全且自動析構),或直接刪除複製並搭配 std::call_once。std::shared_ptr)管理生命週期,不必自己寫 Garbo。Free() 的「笨方法」,可作為對照理解為何需要 Garbo 這種自動化手段。