Document directory
The template method mode is the behavior mode of the class. Prepare an abstract class, implement part of the logic in the form of a specific method and a specific constructor, and then declare some abstract methods to force the subclass to implement the remaining logic. Different sub-classes can implement these abstract methods in different ways to implement the rest logic differently. This is the intention of the template method mode.
Structure of the template method mode
The template method mode is one of the most common modes in all modes and is a basic technology based on inherited code reuse.
The template method mode requires collaboration between designers who develop abstract classes and specific sub-classes. One designer is responsible for providing the outline and skeleton of an algorithm, while other designers are responsible for providing the logical steps of this algorithm. The method that represents these specific logical steps is called the basic method. The method that summarizes these basic methods is called the template method ), the name of this design pattern is from here.
The behavior represented by the template method is called top-level behavior, and its logic is called top-level logic. The static structure of the template method mode is as follows:
Two roles are involved:
Abstract template has the following responsibilities:
■ One or more abstract operations are defined to implement sub-classes. These abstract operations are called basic operations, which constitute a step of top-level logic.
■ Defines and implements a template method. This template method is generally a specific method, which provides a skeleton of top-level logic, and the logical composition steps are postponed to subclass implementation in the corresponding abstract operations. The top-level logic may also call some specific methods.
The role of a specific template has the following responsibilities:
■ Implement one or more abstract methods defined by the parent class. They are the composition steps of a top-level logic.
■ Each abstract template role can have any number of specific template roles, and each specific template role can provide these abstract methods (that is, the composition steps of top-level Logic) so that the implementation of the top-level logic is different.
Source code
Abstract template corner classes, abstractmethod (), hookmethod () and other basic methods are the composition steps of top-level logic, which is represented by the templatemethod () method.
Package COM. bankht. template;/*** @ Author: -AK47 * @ Creation Time: 10:30:37 ** @ Class description: Abstract template role class, abstractmethod (), hookmethod () the basic method is the step of the top-level logic. * This top-level logic is represented by the templatemethod () method. */Public abstract class abstracttemplate {/*** Template Method */Public void templatemethod () {// call the basic method abstractmethod (); hookmethod (); concretemethod ();} /*** the declaration of the basic method (implemented by the subclass) must be replaced by the subclass */protected abstract void abstractmethod ();/*** basic method (null method) the subclass can replace */protected void hookmethod () {}/ *** basic method (implemented). The subclass cannot be moved */private final void concretemethod () {// business-related code }}
The role class of the specific template implements the basic method declared by the parent class. The abstractmethod () method represents the residual logic implemented by the forced subclass, And the hookmethod () the method is optional implementation logic, not required.
Package COM. bankht. template;/*** @ Author: -AK47 * @ Creation Time: 10:37:45, December 28, ** @ Class description: The Role class of the specific template, which implements the basic method declared by the parent class, // * The abstractmethod () method represents the residual logic implemented by the forced subclass. // * while the hookmethod () method is optional and not required. */Public class concretetemplate extends abstracttemplate {// Implementation of the Basic Method @ overridepublic void abstractmethod () {// business-related code} // rewrite the parent class method @ overridepublic void hookmethod () {// business-related code }}
The key to the template mode is:Subclass can replace the variable part of the parent class, but it cannot change the top-level Logic represented by the template method.
When defining a new subclass, you should not think about the control process, but the "responsibility" approach. In other words, we should consider which operations must be replaced, which can be replaced, and which cannot be replaced. Using the template mode can clarify these responsibilities.
Methods In Template Method Mode
Template methods can be divided into two categories: Template methods and basic methods.
Template Method
A template method is defined in an abstract class and combines basic operation methods to form a general algorithm or a general-line method.
An abstract class can have any number of template methods, but not limited to one. Each template method can call any number of specific methods.
Basic Method
There are three basic methods: abstract method, concrete method, and Hook method ).
●Abstract method:An abstract method is declared by an abstract class and implemented by a specific subclass. Abstract keywords are used to mark abstract methods in Java.
●Specific Method:A specific method is declared and implemented by an abstract class, but not implemented or replaced by a subclass.
●Hook method:A hook method is declared and implemented by the abstract class, And the subclass is extended. An abstract class usually provides an empty implementation as the default Implementation of the method.
In the preceding example, abstracttemplate is an abstract class with three methods. Abstractmethod () is an abstract method. It is declared as an abstract method by the abstract class and implemented by the subclass. hookmethod () is a hook method, which is declared by the abstract class and provided by default, and is replaced by a subclass. Concretemethod () is a specific method, which is declared and implemented by the abstract class.
Default Hook method
A hook method is often implemented by default by an empty implementation provided by the abstract class. This empty Hook method is called "do nothing hook ". Obviously, this default Hook method has already been seen in the default adaptation mode. A default Adaptation Mode refers to a class that provides a default empty implementation for an interface, so that the subclass of the default adaptive class does not have to provide the Implementation of all methods as the implementation interface, because a specific class usually does not need all methods.
Naming rules
Naming rules are one of the channels for communication between designers. Using appropriate naming rules can help different designers communicate with each other.
The name of the hook method should start with do, which is the standard practice of Java developers familiar with the design mode. In the preceding example, the hookmethod () of the hook method should start with do. In the httpservlet class, the hookmethod () should also follow this naming rule, such as doget () and dopost.
Use Cases
Consider an example of calculating the deposit interest. Assume that the system supports two types of deposit accounts: the money market account and the certificate of deposite account. The deposit interest of these two accounts is different. Therefore, when calculating the deposit interest amount of an account, two different account types must be distinguished.
The total behavior of this system should be to calculate interest, which determines that the top-level logic as a template method mode should be interest calculation. Because interest calculation involves two steps: one basic method gives the Account type, and the other basic method gives the interest percentage. The two basic methods constitute the specific logic, because the account type is different, so the specific logic will be different.
Obviously, the system needs an abstract role to implement top-level behaviors, and leaves the two basic methods as detailed steps to specific sub-classes for implementation. There are two types of accounts to consider: one is the currency market account and the other is the regular account. Shows the system class structure.
Source code
Abstract template role
Package COM. bankht. template;/*** @ Author: -AK47 * @ Creation Time: 11:13:22 ** @ Class description: abstract template Angle class */public abstract class account {/*** template method, calculate the amount of interest ** @ return returns the amount of interest */public final string calculateinterest () {double interestrate = docalculateinterestrate (); string accounttype = docalculateaccounttype (); system. out. println (accounttype); double amount = calculateamount (accounttype); return amount + "*" + interestrate + "=" + (Amount * interestrate );} /*** leave the basic method to the subclass implementation */protected abstract string docalculateaccounttype ();/*** leave the basic method to the subclass implementation */protected abstract double docalculateinterestrate (); /*** basic method, implemented */private double calculateamount (string accounttype) {/*** omitting the relevant business logic */return 7243.00 ;}}
Templates
Package COM. bankht. template;/*** @ Author: -AK47 * @ Creation Time: 11:14:13 ** @ Class description: template-role account */public class cdaccount extends account {@ overrideprotected string docalculateaccounttype () {return "CDA" ;}@ overrideprotected double docalculateinterestrate () {return 0.06 ;}}
Package COM. bankht. template;/*** @ Author: -AK47 * @ Creation Time: 11:13:49 ** @ Class description: template-currency market account */public class moneymarketaccount extends account {@ overrideprotected string docalculateaccounttype () {return "MMA" ;}@ overrideprotected double docalculateinterestrate () {return 0.045 ;}}
Client type
Package COM. bankht. template;/*** @ Author: -AK47 * @ Creation Time: 11:14:30 ** @ Class description: client class */public class client {public static void main (string [] ARGs) {account Account = new moneymarketaccount (); system. out. println ("currency market account interest amount:" + account. calculateinterest (); account = new cdaccount (); system. out. println ("The amount of interest for the regular account is:" + account. calculateinterest ());}}
Run:
MMA currency market account interest amount: 7243.0*0.045 = 325.935cda periodic account interest amount: 7243.0*0.06 = 434.58
Application of the template method mode in Servlet
Anyone who has used servlet knows that in addition to configuring web. XML, they also need to inherit an abstract class called httpservlet. The httpservice class provides a service () method that calls one or more of the seven do methods to respond to client calls. These do methods must be provided by the specific subclass of httpservlet. Therefore, this is a typical template method mode. The source code of the service () method is as follows:
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, 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 logic doGet(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 will always be less maybeSetLastModified(resp, lastModified); doGet(req, resp); } else { resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } } } else if (method.equals(METHOD_HEAD)) { long lastModified = 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 was requested, anywhere on this server. // String errMsg = lStrings.getString("http.method_not_implemented"); Object[] errArgs = new Object[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.
The following is a simple servlet example:
From the class diagram above, we can see that 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"); }}
The preceding example shows that this is a typical template method mode.
Httpservlet acts as an abstract Template
Template Method: the service () method is used.
The basic method is dopost (), doget (), and other methods.
Testservlet assumes a specific template role
Testservlet replaced two of the seven basic methods in the parent class httpservlet, namely, doget () and dopost ().