结构 | ![]() |
意图 | 定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。Te m p l a t e M e t h o d 使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。 |
适用性 |
|
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
1 using System; 2 3 class Algorithm 4 { 5 public void DoAlgorithm() 6 { 7 Console.WriteLine("In DoAlgorithm"); 8 9 // do some part of the algorithm here10 11 // step1 goes here12 Console.WriteLine("In Algorithm - DoAlgoStep1"); 13 // . . . 14 15 // step 2 goes here16 Console.WriteLine("In Algorithm - DoAlgoStep2"); 17 // . . . 18 19 // Now call configurable/replacable part20 DoAlgoStep3();21 22 // step 4 goes here23 Console.WriteLine("In Algorithm - DoAlgoStep4"); 24 // . . . 25 26 // Now call next configurable part27 DoAlgoStep5();28 }29 30 virtual public void DoAlgoStep3()31 {32 Console.WriteLine("In Algorithm - DoAlgoStep3"); 33 }34 35 virtual public void DoAlgoStep5()36 {37 Console.WriteLine("In Algorithm - DoAlgoStep5"); 38 }39 }40 41 class CustomAlgorithm : Algorithm42 {43 public override void DoAlgoStep3()44 {45 Console.WriteLine("In CustomAlgorithm - DoAlgoStep3");46 }47 48 public override void DoAlgoStep5()49 {50 Console.WriteLine("In CustomAlgorithm - DoAlgoStep5");51 }52 }53 54 ///55 /// Summary description for Client.56 /// 57 public class Client58 {59 public static int Main(string[] args)60 {61 CustomAlgorithm c = new CustomAlgorithm();62 63 c.DoAlgorithm();64 65 return 0;66 }67 }