Prototype

パターンの目的

生成すべきオブジェクトの種類を原型となるインスタンスを使って明確にし、それをコピーすることで新たなオブジェクトの生成を行なう。

GoF パターンのクラス図

structure-08-05:prototype

MixJuice 版 Prototype (改善)

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

導入可能性の問題点

p.131 「Prototype パターンの主な問題点として、prototype の各サブクラスが Clone オペレーションを実装しなければならず、これが困難な場合があるということがあげられる。たとえば、すでに存在しているクラスに対して Clone オペレーションを追加することは難しい。」

p.120, line.37-39, The main liability of the Prototype pattern is that each subclass of Prototype must implement the Clone operation, which may be difficult. For example, adding Clone is difficult when the classes under consideration already exist.

対策

既存のクラスに copy() メソッドを追加する。 (Java では clone() という名前はつかえない。)

結果

既存のクラスを Prototype パターンの一部として有効利用できる。

構造

structure-08-09:prototype

module original {
  define abstract class AbstractProduct {...}
  define class ConcreteProduct1 extends AbstractProduct {...}
  define class ConcreteProduct2 extends AbstractProduct {...}
}

module extension extends original {
  class AbstractProduct {
    define abstract AbstractProduct copy();
  }

  class ConcreteProduct1 {
    AbstractProduct copy() {...}
  }

  class ConcreteProduct2 {
    AbstractProduct copy() {...}
  }
}

サンプルコード

関連するパターン


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


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