Java Design Patterns Rookie series (10) Modeling and implementation of template method pattern

Source: Internet
Author: User

Reprint Please specify source: http://blog.csdn.net/lhy_ycu/article/details/39806973


Template method Mode: A skeleton of an algorithm is defined in a method, and some steps are deferred to subclasses. The template method allows subclasses to redefine some of the steps in the algorithm without changing the structure of the algorithm. In short: The template method defines the steps of an algorithm and allows subclasses to provide implementations for one or more steps.

First, UML modeling:



Second, the code implementation:

/** * Example: A template method defines the steps of an algorithm and allows subclasses to provide implementations for one or more steps. *  take a meal as an example: most people like to eat with chopsticks, but some eat with a spoon */abstract class Abstracttemplate {public void Washhands () {System.out.println (" Wash your hands before meals ... "); /** * Extract the way you eat--template method */public abstract void Eatway ();p ublic Void Rest () {System.out.println ("Rest after dinner ...");} Class Eatbychopsticks extends Abstracttemplate {@Overridepublic void Eatway () {System.out.println ("Most people like to eat with chopsticks ...");}} Class Eatbyspoon extends Abstracttemplate {@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 E Atbychopsticks (); At1.eatway (); Abstracttemplate AT2 = new Eatbyspoon (); At2.eatway ();}}

Iii. Summary

Template method Pattern: In an abstract class, there is a main method, and then define 1...N methods, can be abstract, can not be abstract, define subclasses inherit the abstract class, override abstract methods, by invoking the abstract class, implement the call of the subclass.


Java Design Patterns Rookie series (10) Modeling and implementation of 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.