The Strategy design pattern is a behavioral design pattern that defines a family of algorithms, encapsulates each algorithm, and makes them interchangeable. This pattern allows a client to choose an algorithm's behavior at runtime.
Understanding the Template Method Pattern in C#
Example without Strategy Design Pattern
Let's consider a scenario where we have different types of sorting algorithms (e.g., Bubble Sort, Quick Sort, Merge Sort). The client can choose which sorting algorithm to use at runtime. The Strategy pattern is ideal for this scenario.using System; using System.Collections.Generic; namespace WithoutStrategyPattern { class SortingService { public void Sort(List<int> list, string algorithm) { switch (algorithm) { case "BubbleSort": BubbleSort(list); break; case "QuickSort": QuickSort(list, 0, list.Count - 1); break; case "MergeSort": MergeSort(list, 0, list.Count - 1); break; default: Console.WriteLine("Unknown sorting algorithm."); break; } } private void BubbleSort(List<int> list) { Console.WriteLine("Sorting using Bubble Sort"); int n = list.Count; for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { if (list[j] > list[j + 1]) { int temp = list[j]; list[j] = list[j + 1]; list[j + 1] = temp; } } } } private void QuickSort(List<int> list, int low, int high) { if (low < high) { int pi = Partition(list, low, high); QuickSort(list, low, pi - 1); QuickSort(list, pi + 1, high); } } private int Partition(List<int> list, int low, int high) { int pivot = list[high]; int i = (low - 1); for (int j = low; j < high; j++) { if (list[j] < pivot) { i++; int temp = list[i]; list[i] = list[j]; list[j] = temp; } } int temp1 = list[i + 1]; list[i + 1] = list[high]; list[high] = temp1; return i + 1; } private void MergeSort(List<int> list, int left, int right) { if (left < right) { int mid = left + (right - left) / 2; MergeSort(list, left, mid);
Problems in the Non-Pattern Approach
Single Responsibility Principle Violation:The
SortingService
class is responsible for both determining which sorting algorithm to use and implementing the details of each algorithm. This violates the Single Responsibility Principle.Code Duplication:The sorting algorithms are implemented within the
SortingService
class. If additional sorting algorithms need to be added, the class will become increasingly complex and harder to maintain.Poor Extensibility:Adding a new sorting algorithm requires modifying the
SortingService
class. This approach makes it difficult to extend or modify behavior without altering existing code.Tight Coupling:The
SortingService
class is tightly coupled to the specific sorting algorithms. Any change in the sorting logic or the addition of new algorithms directly impacts this class.
- Single Responsibility Principle:With the Strategy Pattern, each sorting algorithm is encapsulated in its own class. The
SortingContext
class only manages the algorithm to use and delegates the sorting task to the strategy object, adhering to the Single Responsibility Principle. - Code Duplication:The sorting algorithms are separated into different strategy classes. This separation reduces code duplication and keeps each sorting algorithm isolated, making it easier to manage and understand.
- Extensibility:Adding a new sorting algorithm involves creating a new class that implements the
ISortStrategy
interface. TheSortContext
class remains unchanged, promoting a more flexible and extensible design. - Loose Coupling:The
SortContext
class is decoupled from the specific sorting algorithms. It relies on theISortStrategy
interface, allowing any concrete implementation to be used interchangeably without modifying the context class.
Revisited Code with Strategy Pattern
Here is how we can implement this pattern:
using System; using System.Collections.Generic; namespace StrategyPattern { // Strategy interface interface ISortStrategy { void Sort(List<int> list); } // Concrete strategy for Bubble Sort class BubbleSort : ISortStrategy { public void Sort(List<int> list) { Console.WriteLine("Sorting using Bubble Sort"); int n = list.Count; for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { if (list[j] > list[j + 1]) { // Swap temp and list[i] int temp = list[j]; list[j] = list[j + 1]; list[j + 1] = temp; } } } } } // Concrete strategy for Quick Sort class QuickSort : ISortStrategy { public void Sort(List<int> list) { Console.WriteLine("Sorting using Quick Sort"); QuickSortRecursive(list, 0, list.Count - 1); } private void QuickSortRecursive(List<int> list, int low, int high) { if (low < high) { int pi = Partition(list, low, high); QuickSortRecursive(list, low, pi - 1); QuickSortRecursive(list, pi + 1, high); } } private int Partition(List<int> list, int low, int high) { int pivot = list[high]; int i = (low - 1); for (int j = low; j < high; j++) { if (list[j] < pivot) { i++; int temp = list[i]; list[i] = list[j]; list[j] = temp; } } int temp1 = list[i + 1]; list[i + 1] = list[high]; list[high] = temp1; return i + 1; } } // Concrete strategy for Merge Sort class MergeSort : ISortStrategy { public void Sort(List<int> list) { Console.WriteLine("Sorting using Merge Sort"); MergeSortRecursive(list, 0, list.Count - 1); } private void MergeSortRecursive(List<int> list, int left, int right) { if (left < right) { int mid = left + (right - left) / 2; MergeSortRecursive(list, left, mid); MergeSortRecursive(list, mid + 1, right); Merge(list, left, mid, right); } } private void Merge(List<int> list, int left, int mid, int right) { int n1 = mid - left + 1; int n2 = right - mid; int[] L = new int[n1]; int[] R = new int[n2]; Array.Copy(list.ToArray(), left, L, 0, n1); Array.Copy(list.ToArray(), mid + 1, R, 0, n2); int i = 0, j = 0; int k = left; while (i < n1 && j < n2) { if (L[i] <= R[j]) { list[k] = L[i]; i++; } else { list[k] = R[j]; j++; } k++; } while (i < n1) { list[k] = L[i]; i++; k++; } while (j < n2) { list[k] = R[j]; j++; k++; } } } // Context class class SortContext { private ISortStrategy _sortStrategy; public void SetSortStrategy(ISortStrategy sortStrategy) { _sortStrategy = sortStrategy; } public void Sort(List<int> list) { _sortStrategy.Sort(list); } } class Program { static void Main(string[] args) { List<int> list = new List<int> { 34, 7, 23, 32, 5, 62 }; SortContext context = new SortContext(); // Using Bubble Sort context.SetSortStrategy(new BubbleSort()); context.Sort(list); Console.WriteLine(string.Join(", ", list)); list = new List<int> { 34, 7, 23, 32, 5, 62 }; // Using Quick Sort context.SetSortStrategy(new QuickSort()); context.Sort(list); Console.WriteLine(string.Join(", ", list)); list = new List<int> { 34, 7, 23, 32, 5, 62 }; // Using Merge Sort context.SetSortStrategy(new MergeSort()); context.Sort(list); Console.WriteLine(string.Join(", ", list)); } } }
Why is the Strategy Pattern Apt for This Scenario?
- Algorithm Selection: It allows the selection of different sorting algorithms at runtime based on the client's needs.
- Encapsulation: Each sorting algorithm is encapsulated in a separate class, promoting the Single Responsibility Principle.
- Interchangeability: Sorting algorithms can be easily swapped without modifying the client code, providing flexibility.
- Maintainability: The implementation of each sorting algorithm is separate from the client, enhancing code maintainability.
- Extensibility: New sorting algorithms can be easily added without changing the existing code.
Why Can't We Use Other Design Patterns Instead?
- Template Method Pattern: The Template Method pattern enforces a fixed sequence of steps in an algorithm. It is not suitable for scenarios where we need to choose different algorithms at runtime.
- Factory Method Pattern: The Factory Method pattern focuses on object creation, not on selecting and encapsulating interchangeable algorithms.
- Decorator Pattern: The Decorator pattern is used to add responsibilities to objects, not to define a family of interchangeable algorithms.
Steps to Identify Use Cases for the Strategy Pattern
- Identify the Need for Interchangeable Algorithms: Look for scenarios where multiple algorithms can be applied to a task, and the choice of algorithm can change at runtime.
- Encapsulate Each Algorithm: Ensure that each algorithm can be encapsulated in a separate class implementing a common interface.
- Provide Flexibility: The pattern should allow clients to choose and switch between algorithms easily.
- Promote Maintainability and Extensibility: Consider the Strategy pattern when you want to promote maintainability by separating algorithm implementation from the client and enable easy addition of new algorithms.
By following these steps and implementing the Strategy pattern, you can create flexible, maintainable, and interchangeable algorithms, providing clients with the ability to choose the best algorithm for their needs at runtime.
Comments
Post a Comment