在 Java 中扩展现有对象以实现 Comparable
目前我的问题是我需要使用一个不允许更改的现有框架,解决我的问题最方便的方法是使用 Comparable 对象。假设我有一个对象 Foo,它没有实现 Comparable,并且不允许我进去更改它以使其成为 Comparable。我的想法是只使用 Bar,它扩展了 Foo 并实现了 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;
}
}
但假设我在某处得到了 Foo 的实例。如何将其变成 Bar 的实例?针对这种情况是否有推荐的替代解决方案?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您绝对需要 Comparable,而不是 Comparator,请使用装饰器(如其他人提到的)
请注意,ComparableFoo 不需要扩展 Foo。在某些情况下,这可能很好,但不是必需的。如果您确实想获取底层 Foo,则可以将其放在一个字段中,并且您可以访问该字段,或者提供一个正式的访问器。
If you absolutely need a Comparable, not a Comparator, use a Decorator (as mentioned by others)
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.
装饰器模式也许会起作用。然而,它的代价是额外装箱对象,所以如果你有很多对象,我不会使用。
如果可以的话,使用
Comparator
实际上要简单得多。事实上,它为您提供了一些 额外 选项,这是Comparable
所没有的,例如定义替代排序顺序。还可以考虑使用泛型。它不仅仅是一个让代码变得更复杂的玩具,它实际上有助于防止某些类型的错误,这些错误可能很难发现,因为它们通常“大部分”工作,然后在添加子类时突然开始失败。
The decorator pattern will maybe work. It comes however at the cost of additionally boxing objects, so I wouldn't use if you have many objects.
If you can, using a
Comparator
is actually much simpler. In fact, it gives you a couple of additional options that you cannot have withComparable
, such as defining alternative sort orders.Also consider using generics. It's not just a toy to make code more complicated, it actually helps preventing a certain type of bugs that can be a pain to discover, because they usually "mostly" work, and then suddenly start failing much later when subclasses are added.
http://docs.oracle.com/javase/7 /docs/api/java/util/Comparator.html
您可以使用 Java Collections 框架和比较器对类进行排序。
http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html
You could sort classes using the Java Collections framework and your Comparator.