Template Method Mode

Source: Internet
Author: User

Template Method Mode

 

 

UML class diagram:

 

Instance implementation code:

 

 

Abstract class AbstractClass {public abstract void PrimitiveOperation1 (); public abstract void PrimitiveOperation2 (); public void TemplateMethod () {PrimitiveOperation1 (); PrimitiveOperation2 (); Console. writeLine () ;}} class ConcreteClassA: AbstractClass {public override void PrimitiveOperation1 () {Console. writeLine (implementation of specific Class A method 1);} public override void PrimitiveOperation2 () {Console. writeLine (implementation of specific class A method 2);} class ConcreteClassB: AbstractClass {public override void PrimitiveOperation1 () {Console. writeLine (implementation of specific class B method 1);} public override void PrimitiveOperation2 () {Console. writeLine (implementation of Class B method 2 );}}


 

Client implementation:

 

         AbstractClass c;         c = new ConcreteClassA();         c.TemplateMethod();         c = new ConcreteClassB();         c.TemplateMethod();         Console.Read();

 

 

Note:

Defines the skeleton of an algorithm in an operation and delays some steps to the subclass. The template method allows the subclass to redefine certain steps of the Algorithm without changing the structure of an algorithm.

The template method mode demonstrates its advantages by moving the unchanged behavior to the superclass and removing repeated code in the subclass.

 

PS: The template method mode is a bit similar to the builder mode. The former is to put stable behaviors into superclasses, and the latter is done by introducing a new builder class.

 

 

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.