Sunday, March 15, 2009

Proxy Class for Making Any Object IComparable

I've been continuing my thinking on the topic of extension methods and selecting items out of an unsorted list. I made some changes to the selection extension methods in order to make them more manageable.

It led me to another topic which is pretty much unrelated. I was thinking about the proxy pattern and trying to find another way to use it. Right now, I only use it in my TextWriter proxy but haven't used it anywhere else. But, as I was working on all of these extension methods, I realized how easy it was to sort and compare objects that were IComparable and it kept my method signatures nice and clean.

The problem is, not everybody uses IComparable and it's not always better to subclass the object just to get it. Instead, I wrote a proxy class that takes your object and gives you an IComparable. I don't really have any uses for it yet and it's not "cooked" enough to be production ready, but it does do the trick and it is an example of the proxy pattern at work.
public class ProxyIComparable<T> : IComparable<T>
{
private T _object;

public IComparer<T> Comparer { get; private set; }
public Comparison<T> Comparison { get; private set; }

public ProxyIComparable(T obj, Comparison<T> comparison)
{
_object = obj;
Comparison = comparison;

Comparer = new ProxyComparer(Comparison);
}

public ProxyIComparable(T obj, IComparer<T> comparer)
{
_object = obj;
Comparer = comparer;

Comparison = new Comparison<T>((x, y) => Comparer.Compare(x, y));
}

public int CompareTo(T other)
{
return Comparison(_object, other);
}

private class ProxyComparer : IComparer<T>
{
private Comparison<T> _comparison;

public ProxyComparer(Comparison<T> comparison)
{
_comparison = comparison;
}

public int Compare(T x, T y)
{
return _comparison(x, y);
}
}
}

No comments:

Post a Comment