Java Template Method)

Source: Internet
Author: User

1. Concept: DefineAlgorithmAnd delay some implementation steps to the subclass.

Move the unchanged behavior to the superclass to remove duplicates in the subclass.CodeTo reflect his advantages.

2. UML diagram:

3. Code:

Public abstract class templete {private void beforeoperation () {system. Out. println ("this Acton before the operation! ");} Private void afteroperation () {system. Out. println (" this Acton after the operation! ");} // It must be postponed to the subclass (Implementation class) to execute protected abstract void operation (); Public void topoperation () {beforeoperation (); Operation (); afteroperation () ;}} public class templeteimpl extends templete {protected void operation () {system. out. println ("the operation action is executed in the method of servicea instance! ") ;}} Public class templettest {public static void main (string [] ARGs) {templete = new templeteimpl (); templete. topoperation ();}}

4. Application scenarios:

1) Implement the unchanged part of an algorithm at one time and leave the variable behavior to the subclass for implementation.

2) common behaviors in each subclass should be extracted and centralized into a common parent class to avoid code duplication. First, identify the differences in the existing code and separate the differences into new operations. Finally, replace these different codes with a template method that calls these new operations.

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.