Currently my issue is that I need to use an existing framework which I am not allowed to change, and the most convenient way to solve my problem is to use Comparable objects. Suppose I have an object Foo, which does not implement Comparable, and I'm not allowed to go in and change it to make it Comparable. My idea was to just use Bar, which extends Foo and implements Comparable.
public class Bar extends Foo implements Comparable
{
public int compareTo( Object o)
{
Foo f = (Foo) o;
if( this.getID() < f.getID() ) return -1;
else if ( this.getID() == f.getID() ) return 0;
else return -1;
}
}
But then suppose I get an instance of Foo somewhere. How do I turn it into an instance of Bar? Is there an a recommended alternative solution to this situation?
If you absolutely need a Comparable, not a Comparator, use a Decorator (as mentioned by others)
public class ComparableFoo implements Comparable<ComparableFoo> {
final Foo foo;
public ComparableFoo(Foo foo) {
this.foo = foo;
}
@Override
public int compareTo(ComparableFoo o) {
Foo other = o.foo;
// do comparison here, e.g.
return foo.getDate().compareTo(other.getDate());
}
}
Note that ComparableFoo need not extend Foo. In some cases that might be nice, but not a requirement. If you really want to get at the underlying Foo, you have it in a field, and you could either access that field, or provide a formal accessor.