创建可链接的方法是否会使执行不佳?
我在说这个:
public class Foo {
public Foo bar() {
// Code
return this;
}
public Foo setBar() {
// Code
return this;
}
}
Foo foo = new Foo();
foo.bar().setBar();
这是否比创建 Foo.Builder
类并使用 Builder.getFoo();
方法获取 Foo
对象更好?
最佳答案
这种模式称为 fluent interface使代码更具可读性。不幸的是,使用非常广泛的 JavaBeans 标准指定 setter 必须有一个 void
返回,返回 this
可能会破坏一些期望匹配精确签名的工具。 There's a good overview here .
关于java - 链接方法模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18908071/