Template Method pattern of Design Pattern

Source: Internet
Author: User

Template Method pattern of Design Pattern

Definition: defines the skeleton of an operation algorithm, and delays some steps to the subclass. The template method allows the subclass to redefine certain steps of an algorithm without changing the structure of an algorithm.

Structure:


<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + yr7A/placement = "brush: java;"> public abstract class AbstractClass {public abstract void primitiveOperation1 (); public abstract void primitiveOperation2 (); public void templateMethod () {primitiveOperation1 (); primitiveOperation2 (); System. out. println () ;}} public class ConcreteClassA extends AbstractClass {@ Overridepublic void primitiveOperation1 () {// TODO Auto-generated method stubSystem. out. println ("Implementation of specific Class A method 1") ;}@ Overridepublic void primitiveOperation2 () {// TODO Auto-generated method stubSystem. out. println ("Implementation of class A method 2") ;}} public class ConcreteClassB extends AbstractClass {@ Overridepublic void primitiveOperation1 () {// TODO Auto-generated method stubSystem. out. println ("Specific Class B method 1") ;}@ Overridepublic void primitiveOperation2 () {// TODO Auto-generated method stubSystem. out. println ("Specific Class B method 2 ");}}Client code:

public class Client {public static void main(String[] args) {AbstractClass abstractClass = null;abstractClass = new ConcreteClassA();abstractClass.templateMethod();abstractClass = new ConcreteClassB();abstractClass.templateMethod();}}

Running result:

Implementation of Class A method 1

Implementation of Class A method 2

Class B method 1

Class B method 2



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.