Java Template Method pattern

Source: Internet
Author: User
Tags naming convention

Template method Mode

An algorithm skeleton is defined in an algorithm, and some algorithms are deferred into subclasses. The template method allows subclasses to redefine some of the steps in the algorithm without changing the structure of the algorithm.

hooks in the algorithm (HOOK): A hook is a method declared in an abstract class, but only an empty or default implementation. The existence of hooks is that subclasses can hook up different points of the algorithm. It is up to the subclass to decide whether or not to hook up. 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.


Source: >  The template method pattern conforms to the Hollywood design principles: don't call (call) us, we'll call (call) youunder Hollywood principles: we allow the underlying components to hook up to the system, but the high-level components determine when and how to use the underlying components. In other words, the way the high-level component treats the underlying component is: "Don't call me, I'll call you." Here is an example of brewing coffee and tea
Import Java.io.bufferedreader;import Java.io.ioexception;import Java.io.inputstreamreader;public abstract class Drinktemplet {public void Preparedrink () {//Template method Boilwater ();//Boiling water brew ();//brewing Pourincup ();//Pour the drink into the cup if ( Customerneedcondiments ()) {//hook function is used to control the method in the template string answer =getuserinput (); addcodiemnts (answer);}} final void addcodiemnts (String condiments) {System.out.println ("4) Add" +condiments+ "to the drink! ");} String Getuserinput () {string answer = "null"; return answer;} final void Pourincup () {System.out.println ("3) pour boiling water into the cup! ");} Boolean customerneedcondiments () {//hook function return false;} abstract void Brew (); final void Boilwater () {System.out.println ("1, hot water! ");}}

  

Import Java.io.bufferedreader;import Java.io.ioexception;import Java.io.inputstreamreader;public class Tea extends drinktemplet{//specific sub-class @overridevoid brew () {System.out.println ("2, drop tea into the cup"); @Overrideboolean customerneedcondiments () {boolean flag =false; System.out.println ("Would you like add some codiments in your tea?" ( y/n) "); BufferedReader br = new BufferedReader (new InputStreamReader (system.in)), try {if (Br.readline (). StartsWith ("Y")) {flag =true;}} catch (IOException e) {//Todo auto-generated catch Blocke.printstacktrace ();} return flag;} String Getuserinput () {string answer = "null"; try {System.out.println ("What do you want add in your tea?"); BufferedReader br = new BufferedReader (new InputStreamReader (system.in)); answer =br.readline ();} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();} return answer;}}

  

Here's an excerpt from a template pattern in someone else's blog: Source: >

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 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 t            Hrough further expensive logic doget (req, resp);                } else {Long ifmodifiedsince = Req.getdateheader (header_ifmodsince); if (Ifmodifiedsince < (lastmodified/1000 *)) {//If the servlet mod time is later, call DoGe  T ()//Round down to the nearest second for a proper compare//a ifmodifiedsince of                    -1 'll always being less maybesetlastmodified (resp, lastmodified);                Doget (req, resp); } else {Resp.setstatus (httpservletrEsponse.                sc_not_modified);            }}} and 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 This means NO Servlets supports whatever//method was requested,            Anywhere on the 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.

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 ().

Java Template Method pattern

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.