Template Method模式

模板方法就是在父类中定义处理流程的框架,在子类中实现具体的处理。

类图

代码示例

AbstractDisplay(只实现了display方法的抽象类)

/**
 * 只实现了display方法的抽象类
 *
 * Created by xuefeihu on 18/4/12.
 */
public abstract class AbstractDisplay {

    /**
     * 交给子类去实现的open
     */
    public abstract void open();

    /**
     * 交给子类去实现的print
     */
    public abstract void print();

    /**
     * 交给子类去实现的close
     */
    public abstract void close();

    public final void display() {
        open();
        for (int i = 0; i < 5; i++) {
            print();
        }
        close();
    }

}

CharDisplay(实现了open print close方法的类)

/**
 * 实现了open print close方法的类
 *
 * Created by xuefeihu on 18/4/12.
 */
public class CharDisplay extends AbstractDisplay {

    private char ch;

    public CharDisplay (char ch) {
        this.ch = ch;
    }

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

    @Override
    public void print() {
        System.out.println(ch);
    }

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

StringDisplay(实现了open print close方法的类)

/**
 * 实现了open print close方法的类
 *
 * Created by xuefeihu on 18/4/12.
 */
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(测试入口)

/**
 * 测试入口
 *
 * Created by xuefeihu on 18/4/12.
 */
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();
    }

}


参考:《图解设计模式》