操作型モードのTemplate Methodモード
1.アルゴリズムを一つの方法で実現することを望むなら、アルゴリズムのいくつかのステップの定義をサブクラスに延期して再定義し、Template Method(テンプレート方法)モード2を使用してもよい.
//
public abstract class AbstractMethod {
abstract void one();
abstract void twe();
void templateMethod(){
switch (hook()) {
case 0:
one();
twe();
break;
case 1:
one();
break;
case 2:
twe();
break;
default:
break;
}
}
protected int hook(){
return 0;
}
}
//
public class FirstMethod extends AbstractMethod{
@Override
void one() {
// TODO Auto-generated method stub
System.out.println("FirstMethod :one() ...");
}
@Override
void twe() {
// TODO Auto-generated method stub
System.out.println("FirstMethod :twe() ...");
}
}
// : hook()
public class SecondMethod extends AbstractMethod{
@Override
void one() {
// TODO Auto-generated method stub
System.out.println("SecondMethod :one() ...");
}
@Override
void twe() {
// TODO Auto-generated method stub
System.out.println("SecondMethod :one() ...");
}
@Override
protected int hook() {
// TODO Auto-generated method stub
return 2;
}
}
//
public class Test {
public static void main(String[] args){
FirstMethod firstMethod = new FirstMethod();
SecondMethod secondMethod = new SecondMethod();
firstMethod.templateMethod();
secondMethod.templateMethod();
}
}
//
FirstMethod :one() ...
FirstMethod :twe() ...
SecondMethod :one() ...
3.まとめ:Template Method(テンプレート方法)モードの目的は、1つの方法でアルゴリズムを実行し、アルゴリズムのいくつかのステップの定義を遅らせることで、他のクラスがこれらのステップを再定義することができるようになる.このモードは通常、開発者間の何らかの制約として機能することができる.開発者はアルゴリズムの枠組みを提供し、別の開発者はアルゴリズムの特定のステップの具体的な実現を提供する.これは、アルゴリズムによって実現されるステップ、またはアルゴリズムの開発者がアルゴリズムのある位置に設定するフック(hook)が必要であるかもしれない.4.参考:http://haolloyin.blog.51cto.com/1177454/333063/