模板方法是在抽象类中最常用的模式了(应该没有之一),它定义一个操作中算法的骨架,而将一些步骤延迟到子类中,使得子类可以不改变一个算法的结构即可重新定义算法的某些步骤。
例如我们要编写一个欢迎界面,如果用户是第一次打开本软件,则弹出一个欢迎的提示。为了能够实现复用,将这个机制当成一个基类,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();
}
}
Java设计模式之从[欢迎界面]分析模板方法(Template Method)模式,布布扣,bubuko.com
Java设计模式之从[欢迎界面]分析模板方法(Template Method)模式
原文:http://blog.csdn.net/froser/article/details/24200151