To focus on the programming model aspect, let us write a bubble sort routine to sort an array of the int
, double
, or float
types. In a sort routine, we need to compare adjacent elements to decide whether one should swap the position of the elements. In computer science literature, this is called a comparator. Since we are using generic programming techniques, we can write a generic comparator interface to model the comparison action that would need to be performed while sorting is happening, and we will apply the strategy pattern to provide comparators based on types.
interface IComparatorStrategy<T> { int Execute(T a, T b); }
Even though we can use a single generic implementation for comparing elements, in real life we might need concrete classes that are specific to the types. We will implement two concrete classes for the comparison of integers and doubles.
class IntComparator : IComparatorStrategy<int> ...