JAVA-template design mode
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. (Reference fromJAVA and pattern-Template Method.
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.
=== The above cited blogs of others ====
Sample Code:
Define the top-level template abstraction method:
Package test.edu. havemeals; public abstract class AbsHaveMeals {public final void HaveMealsFlow () {food (); tableWare (); howToHaveMeals ();} public abstract void food (); public abstract void tableWare (); public void howToHaveMeals () {System. out. println ("chew food directly with your mouth and swallow ");}}
Define the specific subclass implementation:
Package edu. test. whotoeat; import test.edu. havemeals. absHaveMeals; public class Cat extends AbsHaveMeals {@ Overridepublic void food () {// TODO Auto-generated method stubSystem. out. println ("cat eating cat food");} @ Overridepublic void tableWare () {// TODO Auto-generated method stubSystem. out. println ("tableware: cat food bowl ");}}
Package edu. test. whotoeat; import test.edu. havemeals. absHaveMeals; public class Chinese extends AbsHaveMeals {@ Overridepublic void food () {// TODO Auto-generated method stubSystem. out. println ("Chinese noodles") ;}@ Overridepublic void tableWare () {// TODO Auto-generated method stubSystem. out. println ("tableware: chopsticks, bowl ");}}
Package edu. test. whotoeat; import test.edu. havemeals. absHaveMeals; public class Patient extends AbsHaveMeals {@ Overridepublic void food () {// TODO Auto-generated method stubSystem. out. println ("patient-specific nutrient solution") ;}@ Overridepublic void tableWare () {// TODO Auto-generated method stubSystem. out. println ("tableware: nutrient solution container, catheter") ;}@ Overridepublic void howToHaveMeals () {System. out. println ("using catheter to directly transport nutrition to the patient's body"); // how to use the template method is not suitable in the subclass, which can be rewritten in the subclass }}
Define the factory that generates the specific subclass:
package test.edu.client;import test.edu.havemeals.AbsHaveMeals;public class HaveMealsFactory {public static AbsHaveMeals getAbsHaveMeals(Class ah){try {return ah.newInstance();} catch (InstantiationException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();}return null; } }
Client class:
package test.edu.client;import edu.test.whotoeat.Cat;import edu.test.whotoeat.Chinese;import edu.test.whotoeat.Patient;public class Client {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubHaveMealsFactory.getAbsHaveMeals(Chinese.class).HaveMealsFlow();HaveMealsFactory.getAbsHaveMeals(Cat.class).HaveMealsFlow();HaveMealsFactory.getAbsHaveMeals(Patient.class).HaveMealsFlow();}}
Running result:
Chinese people eat noodle tableware: chopsticks, the bowl uses the mouth to chew food directly, and the cat eats the cat food tableware: the cat food Special bowl uses the mouth to chew food directly, and the swallow patient's special nutrient solution tableware: nutrient solution container, catheter catheter for direct delivery of nutrition to the patient's body
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 the abstract class, And the subclass is not implemented or replaced.
● 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.
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); } }
You can find many servlet instances on the Internet.