名称 | Template Method |
结构 | |
意图 | 定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。Te m p l a t e M e t h o d 使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。 |
适用性 |
|
Code Example |
1// Template Method 2 3// Intent: "Define the skeleton of an algorithm in an operation, deferring 4// some steps to subclasses. Template Method lets subclasses redefine 5// certain steps of an algorithm without changing the algorithm's structure." 6 7// For further information, read "Design Patterns", p325, Gamma et al., 8// Addison-Wesley, ISBN:0-201-63361-2 9 10/* Notes: 11 * If you have an algorithm with multiple steps, and it could be helpful 12 * to make some of those steps replaceable, but no the entire algorithm, then 13 * use the Template method. 14 * 15 * If the programming language in use supports generics / templates (C# does 16 * not), then they could be used here. It would be educational to take a 17 * good look at the way algorithms in ISO C++'s STL work. 18 */ 19 20namespace TemplateMethod_DesignPattern 21{ 22 using System; 23 24 class Algorithm 25 { 26 public void DoAlgorithm() 27 { 28 Console.WriteLine("In DoAlgorithm"); 29 30 // do some part of the algorithm here 31 32 // step1 goes here 33 Console.WriteLine("In Algorithm - DoAlgoStep1"); 34 // . . . 35 36 // step 2 goes here 37 Console.WriteLine("In Algorithm - DoAlgoStep2"); 38 // . . . 39 40 // Now call configurable/replacable part 41 DoAlgoStep3(); 42 43 // step 4 goes here 44 Console.WriteLine("In Algorithm - DoAlgoStep4"); 45 // . . . 46 47 // Now call next configurable part 48 DoAlgoStep5(); 49 } 50 51 virtual public void DoAlgoStep3() 52 { 53 Console.WriteLine("In Algorithm - DoAlgoStep3"); 54 } 55 56 virtual public void DoAlgoStep5() 57 { 58 Console.WriteLine("In Algorithm - DoAlgoStep5"); 59 } 60 } 61 62 class CustomAlgorithm : Algorithm 63 { 64 public override void DoAlgoStep3() 65 { 66 Console.WriteLine("In CustomAlgorithm - DoAlgoStep3"); 67 } 68 69 public override void DoAlgoStep5() 70 { 71 Console.WriteLine("In CustomAlgorithm - DoAlgoStep5"); 72 } 73 } 74 75 /// <summary> 76 /// Summary description for Client. 77 /// </summary> 78 public class Client 79 { 80 public static int Main(string[] args) 81 { 82 CustomAlgorithm c = new CustomAlgorithm(); 83 84 c.DoAlgorithm(); 85 86 return 0; 87 } 88 } 89} 90 |