模板方法模式是通过把不变行为搬移到超类,而超类一定会定义为虚类虚方法,虚方法在每个子类中重写,去除子类中的重复代码来体现它的优势。
通用模式样例代码为:
1 /* 2 * Created by SharpDevelop. 3 * User: home 4 * Date: 2013/4/24 5 * Time: 21:42 6 * 7 * To change this template use Tools | Options | Coding | Edit Standard Headers. 8 */ 9 using System; 10 11 namespace template 12 { 13 abstract class AbstractClass 14 { 15 public abstract void PrimitiveOperation1(); 16 public abstract void PrimitiveOperation2(); 17 18 public void TemplateMethod() 19 { 20 PrimitiveOperation1(); 21 PrimitiveOperation2(); 22 Console.WriteLine(""); 23 } 24 } 25 26 class ConcreteClassA : AbstractClass 27 { 28 public override void PrimitiveOperation1() 29 { 30 Console.WriteLine("具体类A方法1实现。"); 31 } 32 public override void PrimitiveOperation2() 33 { 34 Console.WriteLine("具体类A方法2实现。"); 35 } 36 } 37 38 class ConcreteClassB : AbstractClass 39 { 40 public override void PrimitiveOperation1() 41 { 42 Console.WriteLine("具体类B方法1实现。"); 43 } 44 public override void PrimitiveOperation2() 45 { 46 Console.WriteLine("具体类B方法2实现。"); 47 } 48 } 49 50 class Program 51 { 52 public static void Main(string[] args) 53 { 54 AbstractClass c; 55 56 c = new ConcreteClassA(); 57 c.TemplateMethod(); 58 59 c = new ConcreteClassB(); 60 c.TemplateMethod(); 61 62 Console.Read(); 63 } 64 } 65 }
时间: 2024-10-28 04:10:36