Design Mode-template method mode

Source: Internet
Author: User

Recently, we have seen the shadows of design patterns in many occasions. We have been investing in algorithms and data structures for a long time. It is very important to find the design patterns. Sometimes code maintenance, reuse, and scalability are better than pure algorithms. So I picked up Daniel's book "big talk Design Patterns" and referred to the blogs of various big cows on the Internet to start my design patterns journey.

Today, we will introduce the template method mode.

Concept:

Template Method (TemplateMethod): defines the algorithm skeleton in an operation, and delays some specific unique steps to the subclass. The template method is a subclass that can redefine the specific steps of some algorithms without changing the overall structure of the algorithm.

Advantages:

For the parent class, code reuse is implemented and a unified template is provided;

For the base class, avoid code duplication and improve the readability of the program.

The parent class contains abstract methods or excuses. It provides different implementations in sub-classes and completes different tasks of their objects through unified operations.

Sample Code:

Package Pattern;/** template class */abstract class TemplateClass {public abstract void Operation (); public void Method () {Operation ();}} /** Specific class 1 */class ConcreteClassOne extends TemplateClass {public void Operation () {System. out. println ("ConcreteClassOne: 1! ") ;}}/** Specific class 2 */class ConcreteClassTwo extends TemplateClass {public void Operation () {System. out. println (" ConcreteClassTwo perform Operation 2! ") ;}} Public class Pattern {public static void main (String [] args) {try {TemplateClass tempClass = new ConcreteClassOne (); tempClass. method (); tempClass = new ConcreteClassTwo (); tempClass. method ();} catch (Exception e) {System. out. println ("Java exception occurred! ");}}}

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.