【D言語】mixinでSingletonパターン

mixinするとシングルスレッドなSingletonパターンになるテンプレートを書いて見ました。


以下のようになります。


import std.stdio: writeln;

mixin template singleton()
{
    static typeof(this) opCall()
    {
        static typeof(this) instance;
        if(!instance) instance = new typeof(this)();
        return instance;
    }
}

class Hoge
{
    this()
    {
        "Hoge".writeln();
    }

    mixin singleton;
}

void main()
{
    auto hoge = Hoge();
    hoge = Hoge();
}

実行すると


Hoge

ちゃんと、Hogeコンストラクタが1度しか呼ばれないようになっています。

mixinテンプレートは、mixinした場所で展開されるので、typeof(this)がちゃんとHogeになってくれます。 typeof(this)のおかげで、だいぶ簡単に書けています。

担当:美馬(マルチスレッドを考え始めると途端に難しくなるSingletonパターン)