模板方法是在抽象类中最常用的模式了(应该没有之一),它定义一个操作中算法的骨架,而将一些步骤延迟到子类中,使得子类可以不改变一个算法的结构即可重新定义算法的某些步骤。
例如我们要编写一个欢迎界面,如果用户是第一次打开本软件,则弹出一个欢迎的提示。为了能够实现复用,将这个机制当成一个基类,Java代码如下:
abstract class FirstLogin{
abstract protected void showIntro();
boolean firstLogin;
public FirstLogin(boolean firstLogin){
this.firstLogin = firstLogin;
}
public void show(){
if (firstLogin){
showIntro();
}
}
}
class HelloWorld extends FirstLogin{
public HelloWorld(boolean firstLogin) {
super(firstLogin);
}
protected void showIntro(){
System.out.println("欢迎你第一次使用本程序! Hello world!");
}
}
public class TemplateMethod
{
public static void main(String[] args) {
HelloWorld helloWorld1 = new HelloWorld(false);
System.out.println("HelloWorld 1:");
helloWorld1.show();
HelloWorld helloWorld2 = new HelloWorld(true);
System.out.println("HelloWorld 2:");
helloWorld2.show();
}
}
FirstLogin中的show方法为模板方法。它用了showIntro这个抽象方法定义了出现欢迎界面的算法,而它的子类将来实现showIntro方法。也就是说,基类用于实现不变的部分,而将可变的部分留给子类,是十分常见的一种模式。