Java Design Pattern cainiao series (10) template method pattern modeling and implementation

Source: Internet
Author: User

Java Design Pattern cainiao series (10) template method pattern modeling and implementation

 

 

Template Method: defines the skeleton of an algorithm in a Method, and delays some steps to the subclass. The template method allows the subclass to redefine some steps in the algorithm without changing the algorithm structure. In short, the template method defines an algorithm step and allows sub-classes to provide implementation for one or more steps.

I. uml modeling:

 

Ii. Code implementation:

 

/*** Example: the template method defines the steps of an algorithm and allows subclasses to be implemented by one or more steps. ** Taking eating as an example: Most people like to eat with chopsticks, but some still eat with a spoon */abstract class AbstractTemplate {public void into hands () {System. out. println (wash your hands before meals ...);} /*** extract the method of eating --> Template Method */public abstract void eatWay (); public void rest () {System. out. println (rest after meals ...);}} class EatByChopsticks extends AbstractTemplate {@ Overridepublic void eatWay () {System. out. println (most people prefer to eat with chopsticks ...);}} class EatBySpoon extends acttemplate {@ Overridepublic void eatWay () {System. out. println (some eat with a spoon ...);}} /*** client Test class ** @ author Leo */public class Test {public static void main (String [] args) {AbstractTemplate at1 = new EatByChopsticks (); at1.eatWay (); abstractTemplate at2 = new EatBySpoon (); at2.eatWay ();}}

 

Iii. Summary

 

Template Method mode: in an abstract class, there is a main method, and then defines 1... n methods can be abstracted and not abstract. Define sub-classes to inherit the abstract class, override the abstract method, and call the abstract class to call the sub-class.

 

 

Related Article

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.