英文:
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:
>
> accept(t)
> return this;
>
<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<T>
,因此它必须实现 accept(T)
方法。
但是 accept(T)
返回 void
,所以我认为他们添加了 add(T)
以方便使用:在构建器模式实现中,方法通常返回 this
以便能够链接构建过程,最后调用 build()
。
英文:
My guess:
Stream.Builder
extends Consumer<T>
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()
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论