C# 设计模式系列教程-模板方法模式

  ///

  /// 抽象类,定义冒泡排序的骨架

  ///

  public abstract class BubbleSorter

  {

  private int operations = 0;

  protected int length = 0;

  ///

  /// 冒泡排序算法

  ///

  ///

  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;

  }

  ///

  /// 留给子类实现的交换位置方法

  ///

  ///

  protected abstract void Swap(int index);

  ///

  /// 留给子类实现的比较方法

  ///

  ///

  ///

  protected abstract bool OutOfOrder(int index);

  }

  ///

  /// 整型类型的冒泡算法实现

  ///

  public class IntBubbleSorter:BubbleSorter

  {

  private int[] array = null;

  ///

  /// 用冒泡算法排序

  ///

  ///

  ///

  public int Sort(int[] theArray)

  {

  array = theArray;

  length = array.Length;

  // 调用冒泡算法

  return DoSort();

  }

  ///

  /// 实现冒泡算法中的交换操作

  ///

  ///

  protected override void Swap(int index)

  {

  int temp = array[index];

  array[index] = array[index + 1];

  array[index + 1] = temp;

  }

  ///

  /// 实现冒泡算法中的比较操作

  ///

  ///

  ///

  protected override bool OutOfOrder(int index)

  {

  return (array[index] > array[index + 1]);

  }

  }

  ///

  /// 浮点数类型的冒泡算法

  ///

  public class FloatBubbleSorter:BubbleSorter

  {

  private float[] array = null;

  ///

  /// 用冒泡算法排序

  ///

  ///

  ///

  public int Sort(float[] theArray)

  {

  array = theArray;

  length = array.Length;

  // 调用冒泡算法

  return DoSort();

  }

  ///

  /// 实现冒泡算法中的交换操作

  ///

  ///

  protected override void Swap(int index)

  {

  float temp = array[index];

  array[index] = array[index + 1];

  array[index + 1] = temp;

  }

  ///

  /// 实现冒泡算法中的比较操作

  ///

  ///

  ///

  protected override bool OutOfOrder(int index)

  {

  return (array[index] > array[index + 1]);

  }

  }