Template Method mode: defines the skeleton of an algorithm in an operation, and delays some steps to the subclass. The template method allows subclass to redefine certain steps of an algorithm without changing the structure of an algorithm.
AbstractClass is an abstract class, which is actually an abstract class. It defines and implements a template method. This template method is generally a specific method that provides a skeleton of top-level logic, the logical composition steps are postponed to subclass implementation in the corresponding abstract operations. The top-level logic may also call some specific methods.
ConcreteClassA implements one or more abstract methods defined by the parent class. Each AbstractClass can have any number of concreteclasses corresponding to it, and each ConcreteClass can provide different implementations of these abstract methods (that is, the building steps of top-level Logic, so that the implementation of the top-level logic is different.
Public class ConCreteClassA: AbstractClass {public override void PrimitiveOperation1 () {Console. writeLine ("Implementation of specific Class A method 1");} public override void PrimitiveOperation2 () {Console. writeLine ("Implementation of class A method 2") ;}} public 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 ");}}
class Program { static void Main(string[] args) { AbstractClass Test; Test = new ConCreteClassA(); Test.TemplateMethod(); Test = new ConCreteClassB(); Test.TemplateMethod(); Console.ReadLine(); } }
The running result is as follows:
When the immutable and mutable behaviors are mixed in the implementation of the method subclass, the immutable behavior will be repeated in the subclass. We use the template method to move these actions to a single place, which helps subclass to get rid of repeated and unchanged behavior entanglement.