Singleton

パターンの目的

p.137,line.3-4 あるクラスに対してインスタンスが1つしか依存しないことを保証し、それにアクセスするためのグローバルな方法を提供する。

GoF パターンのクラス図

structure-08-05:singleton

MixJuice 版 Singleton (別解)

解決される GoF パターンの問題点

クラス数増加の問題点

p.138,line.24-29: 5.クラスオペレーションよりも柔軟である。Singletonパターンと同等の機能を提供する別の方法として、クラスオペレーション(C++における静的メンバ関数、Smalltalkにおけるクラスメソッド)を用いることもできる。しかし、このような言語上のテクニックで対処する方法では、クラスのインスタンスを1つ以上に変更する場合に困難になる。さらに、C++における静的メンバ関数は仮想関数にすることができないので、サブクラスでポリモルフィックにオーバーライドすることができない。

p.128, line.26-31, The Singleton pattern has several benefits: 5. More flexible than class operations. Another way to package a singleton's functionality is to use class operations (that is, static member functions in C++ or class methods in Smalltalk). But both of these language techniques make it hard to change a design to allow more than one instance of a class. Moreover, static member functions in C++ are never virtual, so subclasses can't override them polymorphically.

補足:クラスオペレーション(Java における static method )を用いた方が、定義および呼び出しの記述が簡潔であるし、呼び出しの実行速度も(おそらく)速い、というメリットがある。 Singleton パターンを使うとこれらのメリットが失われる。

対策

MixJuice の将来のバージョンでは static method もモジュールの追加によって拡張可能なので、グローバルなオペレーションを普通に static method で定義すれば良い。(ただし MJ1.1 では static method の拡張はサポートされていない。)

結果

static method を使って、簡潔にグローバルかつ拡張可能なオペレーションが定義できる。その代わり、結果の節の4項目めに書いてある「インスタンスの数を変えることができる。」という Singleton パターンの利点の1つは享受できない。

構造

structure-08-09:singleton

module original {
  define class C {
    define static void operation() {...}
    define static int data;
  }
}

module extension extends original {
  class C {
    static void operation() { ... original() ...}
  }
}

サンプルコード

関連するパターン


MixJuice によるデザインパターン改善カタログ


田中 哲 <akr@m17n.org>, 一杉 裕志 <y-ichisugi@aist.go.jp>