Design Pattern VI: Template method

Source: Internet
Author: User
Tags prepare
Brief introduction

The template method is one of the behavioral patterns.

At the implementation level, the skeleton of an algorithm or process is defined in an abstract class, and the variable part is deferred to the subclass implementation, which allows its subclasses to implement some of these steps.

The template method is appropriate for the algorithm, but some of the steps in the algorithm change, such as the JDBC transaction operation in spring, opening the connection--opening the transaction--executing the sql--> COMMIT transaction--and closing the connection, each operation follows this step. The difference is that the SQL executed is not the same.

Intention

Define the algorithm framework and defer implementation of some of the steps to the subclass implementation.

Class diagram

Realize

I. Define an abstract class and encapsulate the skeleton definition of the algorithm into a method, notice that the method is final decorated to prevent someone from inheriting the class and making malicious modifications to the algorithm, and the invariant steps can be implemented

/** * 磨坊 */public abstract class MillTemplate {    /**     * 模板方法,定义步骤     */    public final void produce(){        //准备(可能是小麦,也可能是玉米)        prepare();        //开机器        start();        //包装        packaging();        //运输(可能水路也可能火车)        transport();    }    //准备(可能是小麦,也可能是玉米)    protected abstract void prepare();    private void start(){        System.out.println("启动机器, 开始研磨...");    }    private void packaging(){        System.out.println("包装...");    }    //运输(可能水路也可能火车)    protected abstract void transport(); }

Two. Define subclasses to inherit abstract classes and implement abstract methods

/** * 玉米磨坊 */public class CoreMill extends MillTemplate {    protected void prepare() {        System.out.println("准备好玉米");    }    protected void transport() {        System.out.println("火车运输");    }}
/** * 小麦磨坊 */public class WheatMill extends MillTemplate {    protected void prepare() {        System.out.println("准备好小麦");    }    protected void transport() {        System.out.println("船运");    }}

Three. Call

public class TemplateTest {    public static void main(String[] args) {        MillTemplate millTemplate = new WheatMill();        millTemplate.produce();        millTemplate = new CoreMill();        millTemplate.produce();    }}

Four. Hook method, Hook method provides more flexibility for the template algorithm, subclasses can control some steps or not execute according to the result of the hook method

We add the hook method to the template method

.../*** 模板方法,定义步骤*/public final void produce(){    //准备(可能是小麦,也可能是玉米)    prepare();    //开机器    start();    //包装    packaging();    //检查的钩子方法    if(needRecheck()){        recheck();    }    //运输(可能水路也可能火车)    transport();}...//钩子方法protected boolean needRecheck(){    return true;}//检查private void recheck(){    System.out.println("检查...");}...

The subclass overload Hook method has reached the goal of whether a step of the control algorithm is executed

//WheatMill 中增加@Overrideprotected boolean needRecheck(){    return false;}
Summarize

Advantages: 1. The invariant part is encapsulated and the variable part is easy to expand; 2. Easy code reuse for easy maintenance

Cons: Each different implementation requires a subclass, which increases the number of classes and the system is too large

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.