C# 設計模式系列教程-模板方法模式_C#教程

來源:互聯網
上載者:User

1. 概述

  定義一個操作中的演算法的骨架,而將步驟延遲到子類中。模板方法使得子類可以不改變一個演算法的結構即可重定義演算法的某些特定步驟。

2. 模式中的角色

  2.1 抽象類別(AbstractClass):實現了模板方法,定義了演算法的骨架。

  2.2 具體類(ConcreteClass):實現抽象類別中的抽象方法,已完成完整的演算法。

3. 模式解讀

  3.1 模板方法類圖

  3.2 模板方法模式代碼實現

 /// <summary> /// 抽象類別 /// </summary> public abstract class AbstractClass {  // 一些抽象行為,放到子類去實現  public abstract void PrimitiveOperation1();  public abstract void PrimitiveOperation2();  /// <summary>  /// 模板方法,給出了邏輯的骨架,而邏輯的組成是一些相應的抽象操作,它們延遲到子類去實現。  /// </summary>  public void TemplateMethod()  {   PrimitiveOperation1();   PrimitiveOperation2();   Console.WriteLine("Done the method.");  } } /// <summary> /// 具體類,實現了抽象類別中的特定步驟 /// </summary> public class ConcreteClassA : AbstractClass {  /// <summary>  /// 與ConcreteClassB中的實現邏輯不同  /// </summary>  public override void PrimitiveOperation1()  {   Console.WriteLine("Implement operation 1 in Concreate class A.");  }  /// <summary>  /// 與ConcreteClassB中的實現邏輯不同  /// </summary>  public override void PrimitiveOperation2()  {   Console.WriteLine("Implement operation 2 in Concreate class A.");  } } /// <summary> /// 具體類,實現了抽象類別中的特定步驟 /// </summary> public class ConcreteClassB : AbstractClass {  /// <summary>  /// 與ConcreteClassA中的實現邏輯不同  /// </summary>  public override void PrimitiveOperation1()  {   Console.WriteLine("Implement operation 1 in Concreate class B.");  }  /// <summary>  /// 與ConcreteClassA中的實現邏輯不同  /// </summary>  public override void PrimitiveOperation2()  {   Console.WriteLine("Implement operation 2 in Concreate class B.");  } }

  3.3 用戶端代碼

 class Program {  static void Main(string[] args)  {   // 聲明抽象類別   AbstractClass c;   // 用ConcreteClassA執行個體化c   c = new ConcreteClassA();   c.TemplateMethod();   // 用ConcreteClassB執行個體化c   c = new ConcreteClassB();   c.TemplateMethod();   Console.Read();  } }

  運行結果

5. 模式總結

  5.1 優點

    5.1.1 模板方法模式通過把不變的行為搬移到超類,去除了子類中的重複代碼。

    5.1.2 子類實現演算法的某些細節,有助於演算法的擴充。

    5.1.3 通過一個父類調用子類實現的操作,通過子類擴充增加新的行為,符合“開放-封閉原則”。

  5.2 缺點

    5.2.1 每個不同的實現都需要定義一個子類,這會導致類的個數的增加,設計更加抽象。

  5.3 適用情境

    5.1 在某些類的演算法中,用了相同的方法,造成代碼的重複。

    5.2 控制子類擴充,子類必須遵守演算法規則。

6. 模式舉例: 用冒泡演算法非別對整型數組、浮點數數組、日期數組實現排序。

  6.1 實作類別圖

  6.2 實現代碼

 /// <summary> /// 抽象類別,定義冒泡排序的骨架 /// </summary> public abstract class BubbleSorter {  private int operations = 0;  protected int length = 0;  /// <summary>  /// 冒泡排序演算法  /// </summary>  /// <returns></returns>  protected int DoSort()  {   operations = 0;   if (length <= 1)   {    return operations;   }   for (int nextToLast = length - 2; nextToLast >= 0; nextToLast--)   {    for (int index = 0; index <= nextToLast; index++)    {     if (OutOfOrder(index))     {      Swap(index);     }     operations++;    }   }   return operations;  }  /// <summary>  /// 留給子類實現的交換位置方法  /// </summary>  /// <param name="index"></param>  protected abstract void Swap(int index);  /// <summary>  /// 留給子類實現的比較方法  /// </summary>  /// <param name="index"></param>  /// <returns></returns>  protected abstract bool OutOfOrder(int index); } /// <summary> /// 整數型別的冒泡演算法實現 /// </summary> public class IntBubbleSorter:BubbleSorter {  private int[] array = null;  /// <summary>  /// 用冒泡演算法排序  /// </summary>  /// <param name="theArray"></param>  /// <returns></returns>  public int Sort(int[] theArray)  {   array = theArray;   length = array.Length;   // 調用冒泡演算法   return DoSort();  }  /// <summary>  /// 實現冒泡演算法中的交換操作  /// </summary>  /// <param name="index"></param>  protected override void Swap(int index)  {   int temp = array[index];   array[index] = array[index + 1];   array[index + 1] = temp;  }  /// <summary>  /// 實現冒泡演算法中的比較操作  /// </summary>  /// <param name="index"></param>  /// <returns></returns>  protected override bool OutOfOrder(int index)  {   return (array[index] > array[index + 1]);  } } /// <summary> /// 浮點數類型的冒泡演算法 /// </summary> public class FloatBubbleSorter:BubbleSorter {  private float[] array = null;  /// <summary>  /// 用冒泡演算法排序  /// </summary>  /// <param name="theArray"></param>  /// <returns></returns>  public int Sort(float[] theArray)  {   array = theArray;   length = array.Length;   // 調用冒泡演算法   return DoSort();  }  /// <summary>  /// 實現冒泡演算法中的交換操作  /// </summary>  /// <param name="index"></param>  protected override void Swap(int index)  {   float temp = array[index];   array[index] = array[index + 1];   array[index + 1] = temp;  }  /// <summary>  /// 實現冒泡演算法中的比較操作  /// </summary>  /// <param name="index"></param>  /// <returns></returns>  protected override bool OutOfOrder(int index)  {   return (array[index] > array[index + 1]);  } }

  6.3 用戶端調用

 class Program {  static void Main(string[] args)  {   // 對整型數組排序   int[] intArray = new int[]{5, 3, 12, 8, 10};   BubbleSorter.IntBubbleSorter sorter = new BubbleSorter.IntBubbleSorter();   sorter.Sort(intArray);   foreach (int item in intArray)   {    Console.Write(item+" ");   }   Console.WriteLine("");   // 對浮點數排序   float[] floatArray = new float[] { 5.0f, 3.0f, 12.0f, 8.0f, 10.0f };   BubbleSorter.FloatBubbleSorter floatSorter = new BubbleSorter.FloatBubbleSorter();   floatSorter.Sort(floatArray);   foreach (float item in floatArray)   {    Console.Write(item + " ");   }   Console.Read();  } }

  運行結果

以上就是本文的全部內容,希望能給大家一個參考,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.