模板模式定义:定义一个操作中的算法的框架,而将一些步骤延迟到子类中。使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。说的简单点就是准备一个抽象类,将部分逻辑以具体方法以及具体构造函数的形式实现,然后声明一些抽象方法来迫使子类实现剩余的逻辑。不同的子类可以以不同的方式实现这些抽象方法,从而对剩余的逻辑有不同的实现。这就是模板方法模式的用意。模板方法模式是所有模式中最为常见的几个模式之一,是基于继承的代码复用的基本技术。
模板模式类图:
public abstract class Templete
{
private void beforeOperation()
{
System.out.println("This acton before the operation!");
}
private void afterOperation()
{
System.out.println("This acton after the operation!");
}
//需要推迟到子类(实现类) 中执行
protected abstract void operation();
public void topOperation()
{
beforeOperation();
operation();
afterOperation();
}
}
public class TempleteImpl extends Templete
{
protected void operation()
{
System.out.println("The operation action is executed in the method of ServiceA instance! ");
}
}
public class TempletTest
{
public static void main(String[] args)
{
Templete templete = new TempleteImpl();
templete.topOperation();
}
}