将不变的操作(TemplateMethod)提取到父类(AbstractClass)中,而将其它改变的操作延迟到子类(ConcreteClass)中。
AbstractClass:抽象类,PrimitiveOperation方法为抽象方法,具体实现在子类中。TemplateMethod方法调用PrimitiveOperation方法。
ConcreteClass:子类,实现PrimitiveOperation方法。
例子:
1 /// <summary> 2 /// 抽象类,父类 3 /// </summary> 4 public abstract class AbstractClass 5 { 6 public abstract void PrimitiveOperation1(); 7 public abstract void PrimitiveOperation2(); 8 9 public void TemplateMethod() 10 { 11 PrimitiveOperation1(); 12 PrimitiveOperation2(); 13 Console.WriteLine(""); 14 } 15 } 16 17 /// <summary> 18 /// 子类A 19 /// </summary> 20 public class ConcreteClassA : AbstractClass 21 { 22 public override void PrimitiveOperation1() 23 { 24 Console.WriteLine("具体类A方法1实现"); 25 } 26 27 public override void PrimitiveOperation2() 28 { 29 Console.WriteLine("具体类A方法2实现"); 30 } 31 } 32 33 /// <summary> 34 /// 子类B 35 /// </summary> 36 public class ConcreteClassB : AbstractClass 37 { 38 public override void PrimitiveOperation1() 39 { 40 Console.WriteLine("具体类B方法1实现"); 41 } 42 43 public override void PrimitiveOperation2() 44 { 45 Console.WriteLine("具体类B方法2实现"); 46 } 47 } 48 49 public class Opration 50 { 51 static void Main(string[] args) 52 { 53 AbstractClass c; 54 55 c = new ConcreteClassA(); 56 c.TemplateMethod(); 57 58 c = new ConcreteClassB(); 59 c.TemplateMethod(); 60 61 Console.Read(); 62 } 63 }