我正在查看一个名为Product的类,其中包括以下内容:

@JsonProperty("name")
public void setName(String name) {
    this.name = name;
}

public Product withName(String name) {
    this.name = name;
    return this;
}


withName方法的目的是什么?如何使用它?为什么不做:

Product p = new Product();
p.setName("foo");

最佳答案

主要区别在于with方法返回调用该对象的实例。

这样可以进行“流利”的呼叫,例如

 someProductBuilder.withName("bla").withPrice(100)...


从这个意义上说:一种非正式的约定,用于区分普通的二传手与通过返回受影响的对象而允许流畅使用的二传手。

07-28 01:01
查看更多