Java Template Method mode

Source: Internet
Author: User

1. What is a template method?

--a unified framework for algorithm execution, the template method pattern defines an algorithm skeleton in an operation, deferring some steps to the subclass implementation, allowing subclasses to redefine some specific steps of the algorithm without altering the algorithm structure.

----STEP1, Step2 、.... Step N


2.

Template method (define framework using abstract parent class)


Abstract parent class, providing an algorithmic framework for all subclasses


Steps:

(1), define a common abstract parent class

(2), define a public final method (encapsulates the algorithm framework that all subclasses follow)

(3), the method defined in the framework of the algorithm sub-class implementation of the same using private decoration of the method and implementation, the subclass implementation method is not the same as the use of protected abstact decoration of the method and do not implement

(4), let subclasses override the methods that are not implemented by the parent class, implement their own methods

(5), the instance object in the call takes the parent class instance name = new subclass, in the direct call follows the framework method


Example 1:

/* Abstract parent class, provide an algorithmic framework for all subclasses * Step 1: Enter the number * Step 2: Fill in the document * Step 3: Wait for the calling * Step 4: Window processing * */public abstract class Template {//Definition One A public final method (encapsulates the algorithm framework that all subclasses follow) publicly final void Preparetemplate () {//Enter the number Takenum ();//fill in the document Writedoc ();// Wait for the station-to-station waitcallnum ();//window for handle ();} The method subclasses defined in the algorithm framework implement the same method using private adornment and implement the private void Takenum () {System.out.println ("door fetch number");} private void Waitcallnum () {System.out.println ("waiting for a station-to-Station");} The subclass implementation method is not the same as using protected abstact to decorate the method and does not implement protected abstract void Writedoc ();p rotected abstract void handle ();}
public class Example extends template{@Overrideprotected void Writedoc () {//TODO auto-generated method stubSystem.out.pr Intln ("Fill in the deposit document"); @Overrideprotected void handle () {//TODO auto-generated method stubSystem.out.println ("Processing deposit");}}

public class Example2 extends template{@Overrideprotected void Writedoc () {//TODO auto-generated method STUBSYSTEM.OUT.P Rintln ("Fill in the transfer document"); @Overrideprotected void handle () {//TODO auto-generated method StubSystem.out.println ("process transfer");}

Test:

public class Test {public static void main (string[] args) {//TODO auto-generated method stubtemplate template = new Examp Le (); Template.preparetemplate (); System.out.println ("-------------------"); template = new Example2 (); Template.preparetemplate ();}}

Output Result:

Enter the number to fill in the deposit document waiting for the number of processing deposit-------------------the door to fill in the transfer document waiting for the transfer


3. You can use the hook method to make the template method mode more flexible

Using the hook function to implement the subclass of the algorithm framework to personalize the expansion (simply by the hook dynamically add steps)

Thought

(1), the framework through the provision of a hook, so that the framework has greater flexibility. Do not want to perform some of the steps in the algorithm framework, we can decouple, if we want to execute, we can hook.

Realize

(2), in the abstract class, provides the protected hook method. This is an implemented or empty method. This way the class can choose to overwrite-hold the hook, or you can choose not to overwrite-check.

Use

(3), provide a isxxx type of hook method. This method is used to control the algorithm framework.

Whether a step executes

(4), the subclass does not overwrite this method, is decoupling, still executes according to the framework logic, once overwrite, is the hook, will change the frame algorithm direction, executes according to the subclass logic.

Example 2:

/* Abstract parent class, provide an algorithmic framework for all subclasses * Step 1: Enter the number * Step 2: Fill in the document * Step 3: Wait for the station calls * Step 4: Window processing * Step 5: Whether you need to go to the special window (according to user selection) * */public Abstract class Template {//defines a public final method that encapsulates the algorithm framework that all subclasses follow) public final void Preparetemplate () {//door fetch number takenum ();// Fill in the document Writedoc ();//wait for the station-to-station waitcallnum ();//window for handle (); if (Ishandleagain ()) {handle ();}} The method subclasses defined in the algorithm framework implement the same method using private adornment and implement the private void Takenum () {System.out.println ("door fetch number");} private void Waitcallnum () {System.out.println ("waiting for a station-to-Station");}  The subclass implementation method is not the same as using protected abstact to decorate the method and does not implement protected abstract void Writedoc ();p rotected abstract void handle ();/* Hook, A hook function that provides a default or empty implementation * The specific subclass can decide for itself whether to hook and how to hook * Ask the user whether to add seasoning */protected Boolean ishandleagain () {return false;}}

public class Example3 extends template{@Overrideprotected void Writedoc () {//TODO auto-generated method STUBSYSTEM.OUT.P Rintln ("Fill in Documents");} @Overrideprotected void handle () {//TODO auto-generated method StubSystem.out.println ("process document"); Need to Hook @overrideprotected boolean ishandleagain () {//TODO auto-generated method Stubreturn true;}}
Test:

public class Test {public static void main (string[] args) {//TODO auto-generated method stubtemplate template = new Examp Le (); Template.preparetemplate (); System.out.println ("-------------------"); template = new Example2 (); Template.preparetemplate (); System.out.println ("-------------------"); template = new Example3 (); Template.preparetemplate ();}}

Output Result:

Enter the number to fill in the deposit document waiting for the number of processing deposit-------------------the door to fill in the transfer document waiting for the transfer of money-------------------the door to fill in the documents waiting for the number processing document processing documents
5. Summary

Template method Mode

Applicable scenarios:

A, algorithm or operation follows similar logic

B, refactoring (extracting the same code into the parent class)

C, important, complex algorithm, core algorithm design as template algorithm

Advantages:

A, good encapsulation

B, Good reusability

C, shielding details

D, easy to maintain


Cons: Inheritance



Java Template method mode

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.