Templatemethod
UML Class Diagrams:
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 ("Concrete Class A Method 1 implementation"); } public override void PrimitiveOperation2 () { Console.WriteLine ("Concrete Class A Method 2 implementation"); } } Class Concreteclassb:abstractclass {public override void PrimitiveOperation1 () { Console.WriteLine ("Concrete class B Method 1 Implementation"); } public override void PrimitiveOperation2 () { Console.WriteLine ("Concrete class B Method 2 Implementation"); } }
Client implementations:
AbstractClass C; c = new Concreteclassa (); C.templatemethod (); c = new Concreteclassb (); C.templatemethod (); Console.read ();
Description
The skeleton of an algorithm in an operation is defined, and some steps are deferred to subclasses, and the template method allows subclasses to redefine some specific steps of the algorithm without altering the structure of an algorithm.
The template method pattern is to realize its advantage by moving the invariant behavior to the superclass and removing the duplicated code in the subclass.
PS: The template method pattern is somewhat similar to the builder pattern, which is achieved by putting stable behavior in the superclass, which is accomplished by introducing a new builder class.
Resources
-"Liar design Mode"
Template method Mode