模板方法(Template Method)模式:定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。这里的算法的结构,可以理解为你根据需求设计出来的业务流程。特定的步骤就是指那些可能在内容上存在变数的环节。
模版方法模式的结构:
1) 抽象类(Abstract Class):定义了一到多个的抽象方法,以供具体的子类来实现它们;而且还要实现一个模板方法,来定义一个算法的骨架。该模板方法不仅调用前面的抽象方法,也可以调用其他的操作,只要能完成自身的使命。
2) 具体类(Concrete Class):实现父类中的抽象方法以完成算法中与特定子类相关的步骤。下面是模板方法模式的结构图。
类图:
示例代码
应用场景:测验试卷,每位学生提交自己的答案。
抽象类 – TestPaper
public abstract class TestPaper {
private Integer id;
private Integer score;
public TestPaper(int id){
this.id = id;
}
//getters and setters ...
//此处为模版方法
public void testQuestion() {
System.out.print ("问题与回答为:1+1=");
System.out.println (this.getAnswer ());
}
public abstract String getAnswer();
}
具体类 – TestPaperA 、TestPaperB
public class TestPaperA extends TestPaper {
public TestPaperA(int id) {
super (id);
}
public String getAnswer() {
return "2";
}
}
public class TestPaperB extends TestPaper {
public TestPaperB(int id) {
super (id);
}
public String getAnswer() {
return "1";
}
}
测试:
public class Main {
public static void main(String[] args) {
TestPaper testPaper = new TestPaperA (1);
testPaper.testQuestion ();
testPaper = new TestPaperB (2);
testPaper.testQuestion ();
}
}
output:
1.问题与回答为:1+1=2
2.问题与回答为:1+1=1
总结
模版方法模式的优点:
1、模板方法模式在定义了一组算法,将具体的实现交由子类负责。
2、模板方法模式是一种代码复用的基本技术。
3、模板方法模式导致一种反向的控制结构,通过一个父类调用其子类的操作,通过对子类的扩展增加新的行为,符合“开闭原则”。
模版方法模式的缺点:
每一个不同的实现都需要一个子类来实现,导致类的个数增加。