Strategy Pattern Code Review

Define the Pattern Interface and Handler Objects

Code Download

  • Download Description:strategy pattern download
  • .NET Framework:3.5
  • .NET Language:C#
  • Date Published:2009-07-01
  • Download Size:9 KB

Code Review

Code Walkthrough

Define the IStrategy interface to be used as the "blueprint" for the main application classes.

interface IStrategy { void Sort(List<String> list); }

This interface defines the Sort() method. The Sort() method represents the different sort functions that can be applied.

The QuickSortStrategy class (object) represents a sort pattern that implements a quick sort algorithm.

class QuickSortStrategy : IStrategy { public void Sort(List<string> list) { list.Sort(); } }

The MergeSortStrategy class (object) represents a sort pattern that implements a merge sort algorithm.

class MergeSortStrategy : IStrategy { public void Sort(List<String> list) { String[] dataArray = this.MergeSort(list.ToArray()); list.Clear(); list.AddRange(dataArray); } private String[] SplitArray(String[] data, Int32 lower, Int32 upper) { String[] sub = new String[upper - lower + 1]; for (Int32 i = lower; i <= upper && i < data.Length; i++) { sub[i - lower] = data[i]; } return sub; } private String[] MergeSort(String[] data) { if (data.Length == 1) return(data);
Int32 middle = data.Length / 2;
String[] left = this.MergeSort(this.SplitArray(data, 0, middle - 1)); String[] right = this.MergeSort(this.SplitArray(data, middle, data.Length - 1)); String[] result = new String[data.Length];
Int32 dPtr = 0; Int32 lPtr = 0; Int32 rPtr = 0;
while (dPtr < data.Length) { if (lPtr == left.Length) { result[dPtr] = right[rPtr]; rPtr++; } else if (rPtr == right.Length) { result[dPtr] = left[lPtr]; lPtr++; } else if(String.Compare(left[lPtr],right[rPtr]) < 0) { result[dPtr] = left[lPtr]; lPtr++; } else { result[dPtr] = right[rPtr]; rPtr++; } dPtr++; } return(result); } }

The ShellSortStrategy class (object) represents a sort pattern that implements a shell sort algorithm.

class ShellSortStrategy : IStrategy { public void Sort(List<string> list) { String[] dataArray = this.ShellSort(list.ToArray()); list.Clear(); list.AddRange(dataArray); } private String[] ShellSort(String[] data) { Int32 size = data.Length; Int32 increment = size;
while (increment >= 1) { increment /= 3; if(increment < 1) increment = 1;
for(Int32 i = 0; i < increment; i++) { Int32 j = i + increment;
while(j <= (size - 1)) { Int32 k = j;
while(String.Compare(data[k - increment], data[k]) > 0) { String temp = data[k - increment]; data[k - increment] = data[k]; data[k] = temp; k = k - increment; if ((k-increment) < 0) break; } j+=increment; } } if(increment == 1) break; } return (data); } }