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.
PublicAbstractClassabstracttemplate {/*** Template Method*/PublicvoidTemplatemethod () {//Calling the Basic methodAbstractmethod (); Hookmethod (); Concretemethod (); }/** * declaration of the Basic method (implemented by subclasses) */abstract void Abstractmethod (); /** * Basic method (empty method) */protected void Hookmethod () {} /** * Basic method (already implemented) */ Span style= "color: #0000ff;" >private final void// business-related code /span>
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 class concretetemplate extends abstracttemplate{ // @Override Span style= "color: #0000ff;" >public void Abstractmethod () {// business-related code // methods of overriding the parent class @Override public void Hookmethod () {//< Span style= "color: #008000;" > 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
PublicAbstractClassAccount {/*** Template method, calculate interest Amount *@returnReturn Interest Amount*/PublicFinalDoubleCalculateinterest () {Double interestrate =Docalculateinterestrate (); String AccountType =Docalculateaccounttype ();Double amount =Calculateamount (AccountType);Return amount *InterestRate; }/*** Basic methods are left to subclass implementations*/Protectedabstract String Docalculateaccounttype (); /***/abstract double Docalculateinterestrate (); /** * Basic method, already implemented */private double Calculateamount (String AccountType) { Span style= "color: #008000;" >/** * omit the related business logic */
Specific template Role Classes
Extends account { @Override protectedreturn ' money market 'doublereturn 0.045;}
Extends account { @Override protectedreturn "Certificate of Deposite"doublereturn 0.06 ; }}
Client class
Class Client { voidnew moneymarketaccount (); System.out.println ("Money Market account interest Amount is:" +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:
ProtectedvoidService (HttpServletRequest req, HttpServletResponse resp)ThrowsServletexception, IOException {String method =Req.getmethod ();If(Method.equals (Method_get)) {Long lastmodified =Getlastmodified (req);if (lastmodified = =-1) {//Servlet doesn ' t support if-modified-since, no reason//To go through further expensive logicDoget (req, resp); }Else{Long ifmodifiedsince =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);} } }ElseIf(Method.equals (Method_head)) {Long lastmodified =Getlastmodified (req); Maybesetlastmodified (resp, lastmodified); Dohead (req, resp); }ElseIf(Method.equals (Method_post)) {DoPost (req, resp);}ElseIf(Method.equals (Method_put)) {DoPut (req, resp);}ElseIf(Method.equals (Method_delete)) {DoDelete (req, resp);}ElseIf(Method.equals (method_options)) {dooptions (REQ,RESP);}ElseIfelse {//// Note that this means NO servlet supports whatever //< Span style= "color: #008000;" > method is requested, anywhere on the this server. // String errmsg = lstrings.getstring ("Http.method_not _implemented "); object[] Errargs = "; 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 class Testservlet extends HttpServlet { Public void Doget (HttpServletRequest request, HttpServletResponse response) throws servletexception , IOException {System.out.println ("using the GET method" public void DoPost (HttpServletRequest request, HttpServletResponse response) throws servletexception , 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 ().
The template method mode of Java and pattern (go)