| Structure |
|
| Intention |
Defines the skeleton of an algorithm in an operation, and delays some steps into subclasses. Te m P L a t e m e t h o D allows subclasses to redefine some specific steps of the algorithm without altering the structure of an algorithm. |
| Applicability |
- One-time implementation of an invariant part of the algorithm, and the variable behavior is left to subclass to achieve.
- The public behavior in each subclass should be extracted and centralized into a common parent class to avoid code duplication. This is a good example of the "re-decomposition to generalize" described by O p D y k e and J o h n s o n [o J 9 3]. First identify the differences in the existing code and separate the differences into new operations. Finally, replace these different code with a template method that invokes these new operations.
- Controls the subclass extension. The template method invokes the "H o O K" operation only at a specific point (see the Effects section) so that only those points are allowed to be extended.
|
1 usingSystem;2 3 classalgorithm4 {5 Public voidDoalgorithm ()6 {7Console.WriteLine ("In doalgorithm");8 9 //Do some part of the algorithm hereTen One //Step1 goes here AConsole.WriteLine ("In algorithm-doalgostep1"); - // . . . - the //Step 2 goes here -Console.WriteLine ("In Algorithm-doalgostep2"); - // . . . - + //Now call configurable/replacable part - DoAlgoStep3 (); + A //Step 4 goes here atConsole.WriteLine ("In algorithm-doalgostep4"); - // . . . - - //Now call Next configurable part - DoAlgoStep5 (); - } in - Virtual Public voidDoAlgoStep3 () to { +Console.WriteLine ("In algorithm-doalgostep3"); - } the * Virtual Public voidDoAlgoStep5 () $ {Panax NotoginsengConsole.WriteLine ("In algorithm-doalgostep5"); - } the } + A classCustomalgorithm:algorithm the { + Public Override voidDoAlgoStep3 () - { $Console.WriteLine ("In customalgorithm-doalgostep3"); $ } - - Public Override voidDoAlgoStep5 () the { -Console.WriteLine ("In customalgorithm-doalgostep5");Wuyi } the } - Wu /// <summary> - ///Summary description for Client. About /// </summary> $ Public classClient - { - Public Static intMain (string[] args) - { ACustomalgorithm C =Newcustomalgorithm (); + the c.doalgorithm (); - $ return 0; the } the}Template Method
Template method for behavioral design patterns