print 'Hello YKazu'

('Python', 'Javascript')

【GoF】Template Methodパターン

ポイント

  • 全体のアルゴリズムを、テンプレートクラスに定義
  • アルゴリズムの中で呼び出される機能を、サブクラスに定義
  • テンプレートクラスとサブクラスは1:nの関係

AbstractDisplay.java テンプレートクラス

public abstract class AbstractDisplay { // 抽象メソッドを持つため、abstract class
    // テンプレートメソッド
    public final void display() { // finalで継承不可
        // テンプレートメソッド内で抽象メソッドを呼び出し、全体のアルゴリズムを記述
        // ⇒変わらないものとして、全体のアルゴリズムを定義
        open();
        for (int i = 0; i < 5; i++) {
            print();
        }
        close();
    }

    // 抽象メソッド定義
    // ⇒変わるものを抽象メソッドとして切り出す
    // ⇒サブクラスで抽象メソッドを定義させる
    public abstract void open();
    public abstract void print();
    public abstract void close();
}

CharDisplay.java サブクラス

public class CharDisplay extends AbstractDisplay {
    private char ch;
    public CharDisplay(char ch) {
        this.ch = ch;
    }

    @Override
    public void open() {
        System.out.print("<<");
    }
    @Override
    public void print() {
        System.out.print(ch);
    }
    @Override
    public void close() {
        System.out.println(">>");
    }
}

StringDisplay.java サブクラス

public class StringDisplay extends AbstractDisplay {
    private String string;
    private int width;

    public StringDisplay(String string) {
        this.string = string;
        this.width = string.getBytes().length;
    }

    @Override
    public void open() {
        printLine();
    }
    @Override
    public void print() {
        System.out.println("|" + string + "|");
    }
    @Override
    public void close() {
        printLine();
    }

    private void printLine() {
        System.out.print("+");
        for (int i = 0; i < width; i++) {
            System.out.print("-");
        }
        System.out.println("+");
    }
}

Main.java テンプレートクラス及びサブクラスを利用

public class Main {
    public static void main(String[] args) {
        // リスコフの置換原則
        AbstractDisplay d1 = new CharDisplay('H');
        AbstractDisplay d2 = new StringDisplay("Hello, world.");
        AbstractDisplay d3 = new StringDisplay("こんにちは");

        // テンプレートメソッドを呼び出す
        d1.display();
        d2.display();
        d3.display();
    }
}

コンストラクタのプロパティ

// コンストラクタ
var Car = function(id){
    this.id = id;
    this.type = "truck";
}
console.log(Car.id);   // undefined
console.log(Car.type); // undefined

Car.id = 3;            
Car.type = 'sedan';

console.log(Car.id);   // 3
console.log(Car.type); // sedan

// インスタンス化
cx5 = new Car(808);

console.log(cx5.id);   // 808
console.log(cx5.type); // truck

cx5.id = 909;
cx5.type = "suv";

console.log(cx5.id);   // 909
console.log(cx5.type); // suv