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.