为什么一个对象应该有一个返回 "this" 的方法?

Why should an object have a method returning "this"?

我最近在 Java JodaTime 库中偶然发现了一个奇怪的细节。

有一个 class Instant 有一个名为 toInstant() 的方法。方法简单returnsthis.

/**
 * Get this object as an Instant by returning <code>this</code>.
 * 
 * @return <code>this</code>
 */
public Instant toInstant() {
    return this;
}

我完全不知道这会有什么帮助。如果你想调用这个方法,你已经需要你希望从中得到的对象。或者这仅仅是为了满足接口?

想象一下不同的方法做事并返回它。你可以:

x.doStuff().andStuff().andStuff(2).otherStuff().OtherStuffToo();

Instant 扩展 AbstractInstant 实现 ReadableInstant.

DateTime等时间对象也是ReadableInstant,所以是的,这是满足一个接口;而且,在这种情况下,您正在查看的部分可能没有多大意义。查看 ReadableInstant 的其他实现,它更有意义。

例如

MutableDateTime dateTime = new MutableDateTime();
// Available because MutableDateTime is a ReadableInstant
Instant instant = dateTime.toInstant();

如果我有 MyInstant extends Instant 那么我可以 return 它作为超类

如我的 martin fowler 所述,返回此允许 FluentInterfaces