Abstract(抽象模板):定义了完整的框架,方法的调用顺序通常已经确定,但是还会定义一些抽象的方法给子类实现
Concrete(具体模板实现类):实现抽象模板中定义的抽象方法,实现具体的功能,组成一个完整逻辑
AbstractTemplate
package design.pattern.template; public abstract class AbstractTemplate { public final void run() { step1(); step2(); } public abstract void step1(); public abstract void step2(); }
ConcreteTemplateA
package design.pattern.template; public class ConcreteTemplateA extends AbstractTemplate{ @Override public void step1() { System.out.println("ConcreteTemplateA step1"); } @Override public void step2() { System.out.println("ConcreteTemplateA step2"); } }
ConcreteTemplateB
package design.pattern.template; public class ConcreteTemplateB extends AbstractTemplate{ @Override public void step1() { System.out.println("ConcreteTemplateB step1"); } @Override public void step2() { System.out.println("ConcreteTemplateB step2"); } }
Client
package design.pattern.template; public class Client { public static void main(String[] args) { AbstractTemplate tmpa = new ConcreteTemplateA(); AbstractTemplate tmpb = new ConcreteTemplateB(); tmpa.run(); tmpb.run(); } }