设计模式 模板方法(Template Pattern)
意图
定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。Te m p l a t e M e t h o d 使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。
实用性
1.一次性实现一个算法的不变的部分,并将可变的行为留给子类来实现。
2.各子类中公共的行为应被提取出来并集中到一个公共父类中以避免代码重复。这是O p d y k e 和J o h n s o n 所描述过的“重分解以一般化”的一个很好的例子[ O J 9 3 ]。首先识别现有代码中的不同之处,并且将不同之处分离为新的操作。最后,用一个调用这些新的操作的模板方法来替换这些不同的代码。
3.控制子类扩展。模板方法只在特定点调用“h o o k ”操作(参见效果一节),这样就只允许在这些点进行扩展。
结构图
Code
1 // Template Method
2 /* Notes:
3 * If you have an algorithm with multiple steps, and it could be helpful
4 * to make some of those steps replaceable, but no the entire algorithm, then
5 * use the Template method.
6 *
7 * If the programming language in use supports generics / templates (C# does
8 * not), then they could be used here. It would be educational to take a
9 * good look at the way algorithms in ISO C++'s STL work.
10 */
11
12 namespace TemplateMethod_DesignPattern
13 {
14 using System;
15
16 class Algorithm
17 {
18 public void DoAlgorithm()
19 {
20 Console.WriteLine("In DoAlgorithm");
21
22 // do some part of the algorithm here
23
24 // step1 goes here
25 Console.WriteLine("In Algorithm - DoAlgoStep1");
26 // . . .
27
28 // step 2 goes here
29 Console.WriteLine("In Algorithm - DoAlgoStep2");
30 // . . .
31
32 // Now call configurable/replacable part
33 DoAlgoStep3();
34
35 // step 4 goes here
36 Console.WriteLine("In Algorithm - DoAlgoStep4");
37 // . . .
38
39 // Now call next configurable part
40 DoAlgoStep5();
41 }
42
43 virtual public void DoAlgoStep3()
44 {
45 Console.WriteLine("In Algorithm - DoAlgoStep3");
46 }
47
48 virtual public void DoAlgoStep5()
49 {
50 Console.WriteLine("In Algorithm - DoAlgoStep5");
51 }
52 }
53
54 class CustomAlgorithm : Algorithm
55 {
56 public override void DoAlgoStep3()
57 {
58 Console.WriteLine("In CustomAlgorithm - DoAlgoStep3");
59 }
60
61 public override void DoAlgoStep5()
62 {
63 Console.WriteLine("In CustomAlgorithm - DoAlgoStep5");
64 }
65 }
66
67 /// <summary>
68 /// Summary description for Client.
69 /// </summary>
70 public class Client
71 {
72 public static int Main(string[] args)
73 {
74 CustomAlgorithm c = new CustomAlgorithm();
75
76 c.DoAlgorithm();
77
78 return 0;
79 }
80 }
81 }