For example, a reverse sort algorithm relies upon another sort algorithm. It simply inverts its behavior. Then, to sort a list of names in reverse phone book order, we can compose the reverse algorithm with the phone book order algorithm. We can express the intent in one point of declaration, rather than in a separate class.
Public Class ReverseComparer(Of T)
Implements IComparer(Of T)
Private _comparer As IComparer(Of T)
Public Sub New(ByVal comparer As _
IComparer(Of T))
_comparer = comparer
End Sub
Public Function Compare( _
ByVal x As T, ByVal y As T) _
As Integer _
Implements IComparer(Of T).Compare
Return _comparer.Compare(y, x)
End Function
End Class
phoneBook.Sort( _
New ReverseComparer(Of PersonName)( _
New PhoneBookComparer))
public class ReverseComparer<T> :
IComparer<T>
{
private IComparer<T> _comparer;
public ReverseComparer(
IComparer<T> comparer)
{
_comparer = comparer;
}
public int Compare(T x, T y)
{
return _comparer.Compare(y, x);
}
}
phoneBook.Sort(
new ReverseComparer<PersonName>(
new PhoneBookComparer()));