4

This is about the compareTo contract that classes can implement.

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.

I have read Why can't I extend an instantiable class with a new value component while preserving the compareTo contract?. It helped answer one or two questions i had.But the below question still remains unanswered to me.

1) If i define the two classes as unrelated,i am free to implement the compareTo method as i want.Agree that.But how am i making the two classes have the is-a/parent-child relationship.Can someone explain whatever Joshua called the "view" method?

4

1 回答 1

4

有人可以解释约书亚所谓的“视图”方法吗?

我将从您在帖子中链接的答案中继续 Jon Skeet 的简单示例:

// 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;
}

compareTo这使您可以自由地在 内部实现一个新的Person,因为不需要与超类保持兼容。如果您需要将您的人视为NamedThing,请调用asNamedThing()以将人的视图简化为具有名称的事物。

请注意,由于这不是 is-a 关系,因此asNamedThing有点误导:您在人内部得到命名事物,而不是碰巧是命名事物的人。这限制了 的适用性compareTo:例如,您不能在其他NamedThings 中对人员进行排序。

于 2013-07-21T17:37:47.050 回答