Java design Pattern Template method mode

Source: Internet
Author: User

In the book "Java and Patterns" of Dr. Shanhong, this describes the template method pattern:

  The template method pattern is the behavior pattern of the class. Prepare an abstract class, implement some of the logic in the form of concrete methods and concrete constructors, and then declare some abstract methods to force subclasses to implement the remaining logic. Different subclasses can implement these abstract methods in different ways, thus having different implementations of the remaining logic. This is the intent of the template method pattern.

structure of the template method pattern

  The template method pattern is one of the most common patterns in all patterns and is the basic technique for code reuse based on inheritance.

The template method pattern requires collaboration between the designer of the abstract class and the specific subclass. A designer is responsible for giving the outline and skeleton of an algorithm, while others are responsible for the various logical steps of the algorithm. The methods that represent these specific logical steps are called basic methods (primitive method), and the method of summarizing these basic methods is called template method, and the name of the design pattern is from here.

The behavior represented by a template method is called a top-level behavior, and its logic is called top-level logic. The static structure diagram for the template method pattern is as follows:

  

There are two characters involved:

  Abstract template roles have the following responsibilities:

  One or more abstract operations are defined to allow subclasses to implement. These abstractions are called basic operations, and they are the constituent steps of a top-level logic.

Defines and implements a template method. This template method is generally a concrete method, it gives a top-level logic of the skeleton, and the logical composition of the steps in the corresponding abstract operation, deferred to the sub-class implementation. It is also possible for top-level logic to invoke some concrete methods.

  The concrete template role also has the following responsibilities:

  Implement one or more of the abstract methods defined by the parent class, which are the constituent steps of a top-level logic.

Each abstract template role can have any number of specific template roles corresponding to it, and each specific template role can give a different implementation of these abstract methods (that is, the constituent steps of top-level logic), so that the implementation of the top-level logic varies.

Source

The basic methods of the abstract template role class,Abstractmethod (),Hookmethod () are the constituent steps of the top-level logic, represented by the Templatemethod() method.

 Public Abstract classAbstracttemplate {/*** Template Method*/     Public voidTemplatemethod () {//calling the basic methodAbstractmethod ();        Hookmethod ();    Concretemethod (); }    /*** Declaration of basic methods (implemented by subclasses)*/    protected Abstract voidAbstractmethod (); /*** Basic method (empty method)*/    protected voidHookmethod () {}/*** Basic method (already implemented)*/    Private Final voidConcretemethod () {//Business-related code    }}

The concrete template role class implements the basic method declared by the parent class, and theAbstractmethod() method represents the remaining logic that enforces the subclass implementation, and the Hookmethod() method is the logic that can be chosen to implement, not the one that must be implemented.

 Public classConcretetemplateextendsabstracttemplate{//the implementation of the basic method@Override Public voidAbstractmethod () {//Business-related code    }    //overriding methods of the parent class@Override Public voidHookmethod () {//Business-related code    }}

The key to template mode is that subclasses can displace the mutable parts of the parent class, but subclasses cannot change the top-level logic represented by the template method.

  Whenever a new subclass is defined, do not think in terms of the flow of control, but in accordance with the "responsibility" thinking. In other words, you should consider which operations must be replaced, which operations can be displaced, and which actions are not replaceable. Using template mode can make these responsibilities clear.

methods in the template method pattern

The methods in the template method can be divided into two main categories: Template method and Basic method.

Template method

A template method is defined in an abstract class that combines basic operational methods to form a total algorithm or a method of total behavior.

An abstract class can have any number of template methods, not limited to one. Each template method can invoke any number of specific methods.

Basic methods

The basic method can be divided into three kinds: abstract method, Concrete method (concrete methods) and hook method.

Abstract Method: An abstract method is declared by an abstract class and implemented by a specific subclass. In the Java language, abstract methods are indicated by the Abstraction keyword.

Concrete Method: A concrete method is declared and implemented by an abstract class, and the subclass is not implemented or replaced.

Hook method: A hook method is declared and implemented by an abstract class, and subclasses are extended. Usually the implementation given by an abstract class is an empty implementation, as the default implementation of the method.

In the example above, Abstracttemplate is an abstract class with three methods. where Abstractmethod () is an abstract method, which is declared by an abstract class as an abstract method and implemented by a subclass; Hookmethod () is a hook method that is declared by an abstract class and provides a default implementation, and is displaced by subclasses. Concretemethod () is a concrete method that is declared and implemented by an abstract class.

Default Hook method

A hook method is often given by an abstract class to an empty implementation as the default implementation of this method. This empty hook method is called "Do nothing Hook". Obviously, this default hook method has already been seen in the default adaptation mode, and a default adaptation mode is that a class provides a default null implementation for an interface, so that the subclass of the default adaptation class does not have to give the implementation of all the methods as the implementation of the interface, because usually a concrete class does not need all the methods.

Naming rules

Naming rules are one of the channels by which designers communicate, and using proper naming conventions can help communicate between different designers.

The name of the hook method should begin with do, which is a standard practice for Java developers who are familiar with design patterns. In the above example, the hook method Hookmethod () should start with do, and in the HttpServlet class, this naming convention, such as Doget (), DoPost (), is also followed.

Usage Scenarios

Consider an example of calculating deposit interest. Suppose the system needs to support two types of deposit accounts, namely money markets account and time deposit (Certificate of deposite) accounts. The interest on deposits in these two accounts is different, so in calculating the deposit interest amount of a depositor, two different types of accounts must be distinguished.

The overall behavior of the system should be to calculate interest, which also determines that the top logic as a template method pattern should be interest calculation. Since interest calculation involves two steps: One basic method gives the account type, and the other basic method gives the percentage of interest. These two basic methods constitute specific logic, because the type of account is different, so the specific logic will be different.

Obviously, the system needs an abstract role to give the implementation of the top-level behavior, and the two as the basic method of the detail step is left to the specific subclass implementation. There are two types of accounts to consider: One is a money market account and the other is a time deposit account. The class structure of the system is as shown.

Source Code

Abstract template Role Class

 Public Abstract classAccount {/*** Template method, calculate interest Amount *@returnreturn Interest Amount*/     Public Final Doublecalculateinterest () {DoubleInterestRate =docalculateinterestrate (); String AccountType=Docalculateaccounttype (); DoubleAmount =Calculateamount (AccountType); returnAmount *InterestRate; }    /*** Basic methods are left to subclass implementations*/    protected AbstractString Docalculateaccounttype (); /*** Basic methods are left to subclass implementations*/    protected Abstract Doubledocalculateinterestrate (); /*** Basic method, already implemented*/    Private DoubleCalculateamount (String accounttype) {/*** Omit the relevant business logic*/        return7243.00; }}

Specific template Role Classes

 Public class extends Account {    @Override    protected  String Docalculateaccounttype () {                return "Money Market";    }    @Override    protecteddouble  docalculateinterestrate () {                  return 0.045;}    }
 Public class extends Account {    @Override    protected  String Docalculateaccounttype () {        return "Certificate of Deposite";    }    @Override    protecteddouble  docalculateinterestrate () {          return 0.06;}    }

Client class

 Public class Client {    publicstaticvoid  main (string[] args) {        new Moneymarketaccount ();        System.out.println ("money Market Account interest Amount is:" + account.calculateinterest ());         New Cdaccount ();        System.out.println ("The interest amount for the recurring account is:" + account.calculateinterest ());}    }

Application of template method pattern in servlet

Anyone who has used a servlet knows that, in addition to the corresponding configuration in Web. XML, it is necessary to inherit an abstract class called HttpServlet. The Httpservice class provides a service () method that invokes one or more of the seven do methods to complete the response to a client invocation. These do methods need to be provided by specific subclasses of the HttpServlet, so this is a typical template method pattern. The following is the source code for the Service () method:

    protected voidService (HttpServletRequest req, HttpServletResponse resp)throwsservletexception, IOException {String method=Req.getmethod (); if(Method.equals (method_get)) {LongLastModified =getlastmodified (req); if(LastModified = =-1) {                //servlet doesn ' t support if-modified-since, no reason//To go through further expensive logicdoget (req, resp); } Else {                LongIfmodifiedsince =Req.getdateheader (header_ifmodsince); if(Ifmodifiedsince < (lastmodified/1000 * 1000)) {                    //If The servlet mod time is later, call Doget ()//Round down to the nearest second for a proper compare//A ifmodifiedsince of-1 would always is lessmaybesetlastmodified (resp, lastmodified);                Doget (req, resp); } Else{resp.setstatus (httpservletresponse.sc_not_modified); }            }        } Else if(Method.equals (Method_head)) {LongLastModified =getlastmodified (req);            Maybesetlastmodified (resp, lastmodified);        Dohead (req, resp); } Else if(Method.equals (method_post)) {DoPost (req, resp); } Else if(Method.equals (method_put)) {DoPut (req, resp); } Else if(Method.equals (Method_delete)) {DoDelete (req, resp); } Else if(Method.equals (method_options)) {dooptions (REQ,RESP); } Else if(Method.equals (method_trace)) {dotrace (REQ,RESP); } Else {            //            //Note that this means NO servlet supports whatever//method is requested, anywhere on the this server. //String errmsg= Lstrings.getstring ("http.method_not_implemented"); Object[] Errargs=NewObject[1]; errargs[0] =method; ErrMsg=Messageformat.format (errmsg, Errargs);        Resp.senderror (httpservletresponse.sc_not_implemented, errmsg); }    }

Of course, this service () method can also be replaced by the quilt class.

A simple servlet example is given below:

    

As you can see from the class diagram above, the Testservlet class is a subclass of the HttpServlet class and replaces the two methods of the parent class: Doget () and Dopost ().

 Public classTestservletextendsHttpServlet { Public voiddoget (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {System.out.println ("Using the GET method"); }     Public voidDoPost (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {System.out.println ("Using the POST method"); }}

As you can see from the example above, this is a typical template method pattern.

  HttpServlet as abstract template role

Template method: served by the service () method.

Basic method: By Dopost (), doget () and other methods.

  Testservlet as a specific template role

    Testservlet replaced two of the seven basic methods in the parent class HttpServlet, respectively Doget () and Dopost ().

  

Java design Pattern Template method mode

Related Article

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.