Template Method

パターンの目的

1つのオペレーションにアルゴリズムのスケルトンを定義しておき、その中のいくつかのステップについては、サブクラスでの定義に任せることにする。 Template Method パターンでは、アルゴリズムの構造を変えずに、アルゴリズム中のあるステップをサブクラスで再定義する。

GoF パターンのクラス図

structure-08-05:templatemethod

MixJuice 版 Template Method (改善)

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

拡張性の問題点

p.351 「2. primitive operation の最小化」

p.329, line.4-7, 2.Minimizing primitive operations. An important goal in designing template methods is to minimize the number of primitive operations that a subclass must override to flesh out the algorithm. The more operations that need overriding, the more tedious things get for clients.

クラス数増加の問題点

対策

hook operation の実装を差分として提供する。

hook operation をサブクラスで拡張するのではなく、差分で拡張することにより、可能な拡張の組合せを増やせる。ただし、ひとつのシステム内ではひとつの組合せしか利用できなくなる。

デフォルトの挙動にするわけにはいかないがそれなりに一般的な実装を差分により与えることができるため、無理に最小化しなくても利用のしやすさが低下しなくて済む。

構造

xxx

サンプルコード

関連するパターン


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


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