在Java中创建不可变bean的可能性有多大?例如,我有不可变的类Person.什么是创建实例和填充私有字段的好方法.公共构造函数对我来说似乎并不好,因为当类在其他应用程序中增长时会出现很多输入参数.谢谢你的任何建议.
public class Person {
private String firstName;
private String lastName;
private List<Address> addresses;
private List<Phone> phones;
public List<Address> getAddresses() {
return Collections.unmodifiableList(addresses);
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public List<Phone> getPhones() {
return Collections.unmodifiableList(phones);
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:更准确地指定问题.
您可以使用构建器模式.
public class PersonBuilder {
private String firstName;
// and others...
public PersonBuilder() {
// no arguments necessary for the builder
}
public PersonBuilder firstName(String firstName) {
this.firstName = firstName;
return this;
}
public Person build() {
// here (or in the Person constructor) you could validate the data
return new Person(firstName, ...);
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样使用它:
Person p = new PersonBuilder.firstName("Foo").build();
Run Code Online (Sandbox Code Playgroud)
乍一看,它可能看起来比具有大量参数的简单构造函数更复杂(并且可能是),但是有一些显着的优点:
Person类和构建器,而无需声明多个构造函数或需要重写创建的每个代码Person:只需向构建器添加方法,如果有人不调用它们,则无关紧要.Person.您可以使用构建器创建多个类似的Person对象,这对于单元测试很有用,例如:
PersonBuilder builder = new PersonBuilder().firstName("Foo").addAddress(new Address(...));
Person fooBar = builder.lastName("Bar").build();
Person fooBaz = builder.lastName("Baz").build();
assertFalse(fooBar.equals(fooBaz));
Run Code Online (Sandbox Code Playgroud)