为什么 Stream.Builder 同时拥有 add 和 accept 两种方法?

huangapple go评论74阅读模式
英文:

Why does Stream.Builder have both add and accept methods?

问题

我正在使用 Stream.Builder,并且我偶然发现这个接口有两个方法 accept(T t)add(T t)。唯一的区别在于前者返回 void,而后者返回一个 Stream.Builder

文档甚至提到这些方法具有相同的默认实现:

> 默认实现的行为如下:
> java > accept(t) > return this; >

<sup>请注意,他们忘记了一个分号,但那是另外一个故事。</sup>

我的问题是:为什么他们要在流构建器中使用两个方法来添加内容?我认为这会使API变得混乱,而我以为他们想要避免这种情况

是否有什么充分的理由这样做呢?

英文:

I was using a Stream.Builder and I stumbled upon the fact that this interface has both the methods accept(T t) and add(T t). The only difference is that the former returns void and the latter returns a Stream.Builder.

The documentation even mentions these methods to have the same default implementation:

> The default implementation behaves as if:
>
&gt; accept(t)
&gt; return this;
&gt;

<sup>Note that they forgot a semicolon, but that's another story.</sup>

My question is: why do they have two methods to add something to the stream builder? I think this clutters the API, and I thought they wanted to avoid that.

Is there any compelling reason to do so?

答案1

得分: 35

我的猜测:

Stream.Builder 扩展了 Consumer&lt;T&gt;,因此它必须实现 accept(T) 方法。

但是 accept(T) 返回 void,所以我认为他们添加了 add(T) 以方便使用:在构建器模式实现中,方法通常返回 this 以便能够链接构建过程,最后调用 build()

英文:

My guess:

Stream.Builder extends Consumer&lt;T&gt; so it must implement the accept(T) method.

But accept(T) returns void, so I think they added add(T) for convenience: methods in a builder pattern implementation often return this to be able to chain the building and finally call build().

huangapple
  • 本文由 发表于 2020年10月6日 19:09:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/64224586.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定