假设你有一个名为
Person
的类,而一个 Person
有诸如 name
、id
、age
等属性。与其在构造函数中设置这些值,我们可以采用以下方法:new Person().withName("Lorem").withId("1234").withAge(29)
with
方法是调用set
方法并返回对象的方法,例如:
public Person withAge(int age) {
this.setAge(age);
return this;
}
在一个当前的项目中,我看到了很多这样的代码,通常有5-10个链接到不同with
方法的链式调用。与在构造函数中设置这些值相比,这样做有什么好处呢?
public Person withAge
。 - msagala25