模板方法Template Method

模板方法:定义一个操作中的算法的骨架,而将一些步骤延迟到子类中,TemplateMethod使得子类可以不改变一个算法的结构即可以重定义该算法得某些特定步骤。

方法模式的特点:把不变的行为搬到超类,去除子类中重复的代码来体现他的优势。

应用场景:需要定义一些顶级逻辑 或者是一个操作中算法的骨架,希望一些步奏的执行推迟到其子类中时 应该考虑模板模式。

例如:考虑一个计算存款利息的例子。假设系统需要支持两种存款账号,即货币市场(Money Market)账号和定期存款(Certificate of Deposite)账号。这两种账号的存款利息是不同的,因此,在计算一个存户的存款利息额时,必须区分两种不同的账号类型。这个系统的总行为应当是计算出利息,这也就决定了作为一个模板方法模式的顶级逻辑应当是利息计算。由于利息计算涉及到两个步骤:一个基本方法给出账号种类,另一个基本方法给出利息百分比。这两个基本方法构成具体逻辑,因为账号的类型不同,所以具体逻辑会有所不同。

设计思想:作为模板的方法定义在父类(父类为抽象类),而方法定义使用抽象方法,实现抽象方法的是子类,要在子类实现方法,才能决定具体的操作。如果在不同的子类执行不同实现就可以发展出不同的处理内容。不过,无论在哪个子类执行任何一种实现,处理的大致流程都还是要依照父类制定的方式。

package com.qinsoft.design;

/**
 * 模板方法模式:行为型
 */
public class TemplateMethod
{

    public static void main(String[] args)
    {
        Template templete = new TempleteImpl();  
        templete.topOperation(); 
    }
}

/**
 * 定义一个骨架
 */
abstract class Template
{
    //顶级逻辑  
    public void topOperation(){  
      //第一步  
      beforeOperation();  
      //第二步  
      operation();  
      //第三步
      afterOperation();  
    }
    //需要在操作前执行的方法  
    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(); 
}
/**
 * 骨架的实现
 */
class TempleteImpl extends Template {  
    @Override  
    protected void operation() {  
      System.out.println("The operation action is executed in the method of ServiceA instance! ");  
    }  
} 

最后输出结果是:

This acton before the operation!
The operation action is executed in the method of ServiceA instance!
This acton after the operation!

原文地址:https://www.cnblogs.com/hnhcc39/p/2681299.html