Java design Pattern----Template Method pattern

Source: Internet
Author: User

Template method is better understood, is to avoid code redundancy, implementation of code to take the function. For example, the most common tea and coffee, two have a lot in common, all need to boil water, all need to pour into the cup, then these repeated methods can be drawn out, placed in the parent class, as for the different methods, write an abstract class, so that different subclasses to rewrite the parent class.

Code

Template class

Package Template;public Abstract class Template {public void prepare () {boilwater (); Brew ();p Ourcup (); Boil public void Boilwater () {System.out.println ("boil Water");} public abstract void Brew ();
Pour in the cup public void Pourcup () {System.out.println ("Pour into the cup");}}

Brew Coffee

Package Template;public class Getcoffee extends template {@Overridepublic void Brew () {System.out.println ("Brew Coffee");}}

Tea

Package Template;public class Gettea extends template {@Overridepublic void Brew () {System.out.println ("tea");}}

Test Class

Package Template;public class Test {public static void main (string[] args) {//tea brewing Gettea tea = new Gettea (); Tea.prepare ();// Brewed coffee Getcoffee coffee=new getcoffee (); Coffee.prepare ();}}

Results

Boil the water and pour the tea into the cup and pour the water into a cup of coffee.

Java design Pattern----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.