模板模式就是提供一个模板给其他类来继承,在java中用抽象类来做模板比较好,因为它可以有自己的实现方法,也可以定义抽象方法给继承类来实现。
public abstract class Template {
public void step1() {
System. out .println("do step1" );
}
public void step2() {
System. out .println("do step2" );
}
public void templateMethod () {
this .step1();
this .step2();
}
}
public class ConcreteTemplate extends Template {
public void templateMethod() {
super .templateMethod();
System. out .println("ConcreteTemplate step" );
}
}
public class TemplateClient {
public static void main(String[] args) {
Template template = new ConcreteTemplate();
template.templateMethod();
}
}