模板方法模式,定义一个操作中算法的骨架,把一些步骤延迟到子类当中.模板方法可以使子类不改变一个算法的结构即可重新定义算法某些特定步骤.
使用继承将重复的代码放在父类中,将特定的代码延迟到子类中.
AbstractClass实现模板方法,定义算法的骨架公共内容, 在ConcreteClass中实现具体的相关算法
import java.util.*;
abstract class AbstractClass {
public abstract void PrimitiveOperation1();
public abstract void PrimitiveOperation2();
public void TemplateFunction() {
PrimitiveOperation1();
PrimitiveOperation2();
System.out.println("");
}
}
class ConcreteClassA extends AbstractClass {
public void PrimitiveOperation1() {
System.out.println("ConcreteClassA -- Primitive Operation1 implementation");
}
public void PrimitiveOperation2() {
System.out.println("ConcreteClassA -- Primitive Operation2 implementation");
}
}
class ConcreteClassB extends AbstractClass {
public void PrimitiveOperation1() {
System.out.println("ConcreteClassA -- Primitive Operation1 implementation");
}
public void PrimitiveOperation2() {
System.out.println("ConcreteClassB -- Primitive Operation2 implementation");
}
}
public class TemplateMethod {
public static void main(String[] args) {
AbstractClass abc;
abc = new ConcreteClassA();
abc.TemplateFunction();
abc = new ConcreteClassB();
abc.TemplateFunction();
}
}