0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

デザインパターン学習メモ:「Template Method」

Posted at

目的

GoF本より引用する。

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

共通処理は親クラス(抽象クラス)で実装しておく。サブクラスによって異なる処理は、それぞれ実装する。
コードの重複がなくなり、保守性が向上する。

実装例

execute()を利用者に使ってもらいたい想定。このメソッドの中で3つのメソッドを呼び出している。

メインの処理となるdoJob()は、サブクラスで実装してもらう。
setUp()とcleanUp()は、基本的にはデフォルト実装を使ってもらうが、もし違うものを使いたいならばサブクラスでオーバーライドする。

Application.java
// AbstractClass役
public abstract class Application {
	protected void setUp() {
		System.out.println("Initializing...");
	}

	protected abstract void doJob();

	protected void cleanUp() {
		System.out.println("Clean up...");
	}

	public void execute() {
		setUp();
		doJob();
		cleanUp();
	}
}
MyApplication.java
// Concrete Class役
public class MyApplication extends Application {

	@Override
	protected void doJob() {
		System.out.println("doing job in my way...");
	}
}

実行例

Main.java
public class Main {

	public static void main(String[] args) {
		Application application = new MyApplication();
		application.execute();
	}
}
結果
Initializing...
doing job in my way...
Clean up...

参考文献

  • エリック ガンマ、ラルフ ジョンソン、リチャード ヘルム、ジョン プリシディース(1999)『オブジェクト指向における再利用のためのデザインパターン 改訂版』本位田 真一、吉田 和樹 監訳、SBクリエイティブ
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?