Singletonパターン

プログラム中にクラスのインスタンス(オブジェクト)が1つしかないことを保証するためのパターン。

仕事中にもちらほら見るのう。

「あ、これはシングルトンかーならインスタンスゲットして・・・」のような
やりとりもよくやる。

実装方法はいろいろあるが、私がいままでやってきた方法で書いてみよう。


// テンプレートにするといいかも
template
class SingletonBase
{
protected:
SingletonBase(){}
virtual ~SingletonBase(){}
public:
static Type* GetInstance()
{
if (m_pInstance == NULL) {
m_pInstance = new Type;
}
return m_pInstance;
}
static void DeleteInstance()
{
if (m_pInstance){
delete m_pInstance;
m_pInstance = NULL;
}
}
private:
static Type* m_pInstance;
};

template
Type* SingletonBase::m_pInstance;

// シングルトンにしたいクラスがあるとしますよ
class ASingleton : public SingletonBase
{
friend class SingletonBase;
private:
ASingleton():m_ValueA(0),m_ValueB(1),m_ValueC(2){}
~ASingleton(){}
public:
void FuncA(){}
void FuncB(){}
void FuncC(){}
private:
int m_ValueA;
int m_ValueB;
int m_ValueC;
};

// めいん〜めいん〜
int main()
{
// 内部でインスタンスが作成される
ASingleton::GetInstance();

// 通常通りメソッドコールしてあげたりする
ASingleton::GetInstance()->FuncA();

// なんども参照する場合はローカルにうつしてからコールすると高速
ASingleton* pInstance = ASingleton::GetInstance();
pInstance->FuncA();

// ほうっておくのは個人的に気持ち悪いのできちんと殺します。
ASingleton::DeleteInstance();


return 0;
}

インスタンス開放関数を定義するかしないか迷いましたが、私の仕事では開放順番がとても重要なので作っておきました。