Strategy Pattern Both Array and ArrayList provide the capability - TopicsExpress



          

Strategy Pattern Both Array and ArrayList provide the capability to sort the objects contained in the collection via the Sort method. In fact, ArrayList.Sort just calls Sort on the underlying array. These methods use the QuickSort algorithm. By default, the Sort method will use the IComparable implementation for each element to handle the comparisons necessary for sorting. Sometimes, though, it is useful to sort the same list in different ways. For example, arrays of strings might be sorted with or without case sensitivity. To accomplish this, an overload of Sort exists that takes an IComparer as a parameter; IComparer.Compare is then used for the comparisons. This overload allows users of the class to use any of the built-in IComparers or any of their own making, without having to change or even know the implementation details of Array, ArrayList, or the QuickSort algorithm. Leaving the choice of comparison algorithm up to the user of the class like this is an example of the Strategy pattern. The use of Strategy lets a variety of different algorithms be used interchangeably. QuickSort itself only requires a way to compare objects to each other. By calling Compare through a provided interface, the caller is free to substitute whatever particular comparison algorithm fits its specific needs. The code for the QuickSort can remain unchanged. Figure 5 Strategy in Action One of the new generic collections in version 2.0 of the .NET Framework, List, also makes heavy use of the Strategy pattern, shown in Figure 5. In addition to the updated Sort method, the find-related methods, BinarySearch, and others all take parameters that allow parts of the respective algorithms to vary based on the needs of the caller. The use of a Predicate delegate in the FindAll method lets the caller use any method as a filter for the List so long as it takes the appropriate object type and returns a Boolean. Combined with anonymous methods (another new C# language feature in version 2.0), clients can easily filter lists based on properties and methods of the objects in the list, without introducing dependencies into the List class itself. Using the Strategy pattern lets complicated processes like sorting be easily modified to fit a callers specific purpose, meaning youll be able to write and maintain less code.
Posted on: Sat, 16 Nov 2013 17:28:07 +0000

Trending Topics



Recently Viewed Topics




© 2015