概述
在面向对象程序设计过程中,程序员常常会遇到这种情况:设计一个系统时知道了算法所需的关键步骤,而且确定了这些步骤的执行顺序,但某些步骤的具体实现还未知,或者说某些步骤的实现与具体的环境相关。
例如:一个人每天会起床、吃饭、做事、睡觉等,其中“做事”的内容每天可能不同。我们把这些规定了流程或格式的实例定义成模板,允许使用者根据自己的需求去更新它,例如,简历模板、论文模板、Word 中模板文件等。
定义
定义一个操作中的算法骨架,而将算法的一些步骤延迟到子类中,使得子类可以不改变该算法结构的情况下重定义该算法的某些特定步骤。它是一种类行为型模式。
简单代码
public class Base{
protected int currentStep;
protected void step1(){}
protected void step2(){}
public void action(){
this.currentStep=1;
step1();
this.currentStep=2;
step2();
}
}
public class Child extends Base {
protected void step1(){
System.out.println("child step"+this.currentStep);
}
protected void step2(){
System.out.println("child step"+this.currentStep);
}
}
public static void main(String[] args){
Child c=new Child();
c.action();
}
输出如下:
child step 1
child step 2
回顾
在以上的代码中 action就是一个模板方法,它定义了实现的模板,而具体的实现则由子类提供。
子类通过重写step1、step2来修改对外的行为。