Template Method パターン

Advertisement

処理のテンプレートを作成

抽象メソッドと、それを利用する実行用メソッドを定義して、処理のテンプレートを作成する。実際にロジックを定義するクラスは、このテンプレートクラスを継承して、抽象メソッドをオーバーライドする。実行時にはテンプレートクラスの実行メソッドを実行するが、この実行メソッドでは内部で呼び出すメソッドがどのように実装されているか知らなくてもよい。

サンプルコード

// テンプレート。calc()とshow()はどのように実装してもよい。
abstract class Template{
    // 各メソッドは abstract とし、実装必須にする。
    abstract protected void calc();
    abstract protected void show();

    // 呼び出されるメソッド。オーバライド禁止 (final)
    public final void drawResult(){
        this.calc();
        this.show();
    }
}

// テンプレートを利用した足し算のクラス
class Plus extends Template{
    int num1;
    int num2;
    int result;

    public Plus(int n1, int n2){
        num1 = n1;
        num2 = n2;
    }

    protected void calc(){
        result = num1 + num2;
    }

    protected void show(){
        System.out.println(num1 + " + " +  num2 + " = "  + result);
    }
}

// テンプレートを利用した引き算のクラス
class Minus extends Template{
    int num1;
    int num2;
    int result;

    public Minus(int n1, int n2){
        num1 = n1;
        num2 = n2;
    }

    protected void calc(){
        result = num1 - num2;
    }

    protected void show(){
        System.out.println(num1 + " - " +  num2 + " = "  + result);
    }
}

// テンプレートを利用した掛け算のクラス
class Multi extends Template{
    int num1;
    int num2;
    int result;

    public Multi(int n1, int n2){
        num1 = n1;
        num2 = n2;
    }

    protected void calc(){
        result = num1 * num2;
    }

    protected void show(){
        System.out.println(num1 + " * " +  num2 + " = "  + result);
    }
}

// 実行してみる。Templete型のクラス変数に代入できるのがポイント(ポリモフィズムの実現)
public class TemplateTest{
    public static void main(String args[]){
        Template plus =  new Plus(20, 20);
        Template minus = new Minus(30, 10);
        Template multi = new Multi(10, 5);

        plus.drawResult();
        minus.drawResult();
        multi.drawResult();
    }
}

実行結果
20 + 20 = 40
30 - 10 = 20
10 * 5 = 50

Advertisement

ショートカット

634トップページ
このカテゴリのトップページに戻る
634ラボ

サイト検索

Google

Web サイト内

Y!ログール