Refactoring Method 66: form template method (shaping template functions)

Source: Internet
Author: User

You have some sub-classes, some of which execute similar operations in the same order, but the details of each operation are different. Put these operations into independent functions, and keep them all with the same signature, so the original functions become the same, and then move the original functions to the superclass.

Motivation: inheritance is a powerful tool to avoid repeated behaviors. Whenever you see similar functions in the two subclasses, You can promote them to the superclass. But what if these functions are not exactly the same? It is still necessary to avoid repetition as much as possible, but the substantial difference between these functions must be maintained.

A common case is that the two functions perform roughly similar operations in the same order, but the operations are different. In this case, we can move the execution sequence to the superclass, and use polymorphism to ensure that each operation remains different. Such a function is called template method ).

 

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.