Definition (Template Method)
Defines a framework for an algorithm in an operation, and delays some steps into subclasses. Enables subclasses to redefine some specific steps of the algorithm without altering the structure of an algorithm.
Enlightenment
The assembly computer generally contains three parts, host, monitor, input device (mouse), and different brands of computer assembly are various, but eventually assembled into a complete computer steps are fixed the same. Define abstract classes, expose the host, monitor, input device (mouse) assembly to specific vendors to achieve, provide a public final assembly method.
/// <summary> ///assembling a computer/// </summary> Public Abstract classAssemblecomputer {/// <summary> ///assembling the host/// </summary> Public Abstract voidBuildmainframepart (); /// <summary> ///assembling the display/// </summary> Public Abstract voidBuildscreenpart (); /// <summary> ///assembly input Device (mouse)/// </summary> Public Abstract voidBuildinputpart (); /// <summary> ///assemble it./// </summary> Public voidAssemble () {Buildmainframepart (); Buildscreenpart (); Buildinputpart (); } } /// <summary> ///Assembling HP Computers/// </summary> Public classAssemblehpcomputer:assemblecomputer { Public Override voidBuildmainframepart () {Console.WriteLine ("assembling the motherboard for your HP PC"); } Public Override voidBuildscreenpart () {Console.WriteLine ("assembling the display of an HP computer"); } Public Override voidBuildinputpart () {Console.WriteLine ("assembling the keyboard and mouse of the HP computer"); } } /// <summary> ///assembling a Dell computer/// </summary> Public classAssembledellcomputer:assemblecomputer { Public Override voidBuildmainframepart () {Console.WriteLine ("assembling the motherboard for a Dell computer"); } Public Override voidBuildscreenpart () {Console.WriteLine ("assembling the display of a Dell computer"); } Public Override voidBuildinputpart () {Console.WriteLine ("assembling a keyboard mouse for a Dell computer"); } }
Advantages and Disadvantages
Enables code reuse in accordance with the "OCP"
The template method pattern defines the implementation steps of the algorithm in the abstract class, delays the implementation of these steps into the specific subclass, and makes all subclasses reuse the code of the parent class, so the template method pattern is a technique of implementing code reuse based on inheritance.
Application Scenarios
When creating complex objects, the algorithm should be independent of the parts of the object and how they are assembled.
When the construction process must allow the constructed object to have different representations.
Behavior class pattern of C # Design Pattern: Template Method pattern