C#模板方法模式
模板方法模式是通過把不變行為搬移到超類,而超類一定會定義為虛類虛方法,虛方法在每個子類中重寫,去除子類中的重復代碼來體現它的優勢。
通用模式樣例代碼為:
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 }總結
- 上一篇: 来自damon的zencart二次开发教
- 下一篇: [转]Servlet3.1规范