麻烦理解来自’Effective Java’的关于compareTo的摘录

这是关于类可以实现的compareTo契约.

there is no way to extend an instantiable class with a new value
component while preserving the compareTo contract, unless you are
willing to forgo the benefits of object-oriented abstraction. The same
workaround applies, too. If you want to add a value component to a
class that implements Comparable, don’t extend it; write an unrelated
class containing an instance of the first class. Then provide a “view”
method that returns this instance. This frees you to implement
whatever compareTo method you like on the second class, while allowing
its client to view an instance of the second class as an instance of
the first class when needed.

我已经阅读了Why can’t I extend an instantiable class with a new value component while preserving the compareTo contract?.它帮助回答了我的一两个问题.但是下面的问题对我来说仍然没有答案.

1)如果我将两个类定义为无关,我可以随心所欲地实现compareTo方法.但是我知道如何使这两个类具有is-a / parent-child关系.可以解释一下Joshua叫“观”方法?

解决方法:

Can someone explain whatever Joshua called the “view” method?

我将继续Jon Skeet在answer that you linked in your post中的简单示例:

// In Jon's code, Person derives from NamedThing
class NamedThing {
    String name;
}

class Person extends NamedThing {
    Date dateOfBirth;
}

“提供视图”而不是“扩展”意味着设计类层次结构如下:

class NamedThing {
    String name;
}

class Person {
    private  NamedThing namedThing;
    // Here is the view method
    public NamedThing asNamedThing() {
        return namedThing;
    }
    // Here is a convenience method for accessing name directly
    public String getName() {
        return namedThing.name;
    }
    Date dateOfBirth;
}

这使您可以在Person中实现新的compareTo,因为不需要保持与超类兼容.如果您需要将您的人员视为NamedThing,请调用asNamedThing()以获取缩小为具有名称的事物的人的视图.

请注意,由于这不是一个is-a关系,asNamedThing有点误导:你在人物中得到了命名的东西,而不是恰好是命名的东西.这限制了compareTo的适用性:例如,您不能在其他NamedThings中对人进行排序.

上一篇:java – 如何编写比较对象的compareTo方法?


下一篇:javaSE Comparable接口中的compareTo()方法