Skip to content

模板方法模式

意图

定义操作中算法的骨架,将某些步骤延迟到子类。子类可重新定义特定步骤而不改变算法结构。

类图

Java 示例

java
public abstract class DataImporter {
    public final void importFile(String path) {
        byte[] raw = readBytes(path);
        String text = decode(raw);
        validate(text);
        save(text);
    }
    protected abstract byte[] readBytes(String path);
    protected String decode(byte[] raw) { return new String(raw, java.nio.charset.StandardCharsets.UTF_8); }
    protected void validate(String text) {
        if (text == null || text.isEmpty()) throw new IllegalArgumentException();
    }
    protected abstract void save(String text);
}

public class CsvImporter extends DataImporter {
    protected byte[] readBytes(String path) {
        try { return java.nio.file.Files.readAllBytes(java.nio.file.Paths.get(path)); }
        catch (Exception e) { throw new RuntimeException(e); }
    }
    protected void save(String text) { System.out.println("save csv: " + text.length()); }
}

finalimportFile 即模板方法,防止子类篡改流程。Servlet servicedoGet/doPost 亦为模板方法。

下一节:访问者模式