UserBuilder builder = new UserBuilder();
builder.addName().addEmail().addPhone().addAge();
User user = builder.builder();
可以通过上述代码完成一个对象的构建就是利用了构造器(Builder)模式,使用多个简单的调用一步一步的构建出一个复杂的对象。
主要解决:这种方法通常对象的子对象需要由一定的算法构成,由于需求的变化,这个复杂对象的子对象的属性经常面临着剧烈的变化,但是将它们组合在一起的算法却相对稳定,而组合体对象个体属性是不稳定的。通过这种方式,如果一个子对象的实例过程需要变动,仅需变动对应模块的代码即可。
使用实例如下:
public class Users {
private final String name;
private final String gender;
private final int age;
private final String email;
private Users(UsersBuilder ub) {
super();
this.name = ub.name;
this.gender = ub.gender;
this.age = ub.age;
this.email = ub.email;
}
public String getName() {
return name;
}
public String getGender() {
return gender;
}
public int getAge() {
return age;
}
public String getEmail() {
return email;
}
@Override
public String toString() {
return "Users [name=" + name + ", gender=" + gender + ", age=" + age + ", email=" + email + "]";
}
public static class UsersBuilder {
final String name;
final String gender;
String email;
int age;
public UsersBuilder(String name, String gender) {
super();
this.name = name;
this.gender = gender;
}
public UsersBuilder setAge(int age) {
this.age = age;
return this;
}
public UsersBuilder setEmail(String email) {
this.email = email;
return this;
}
public String getEmail() {
return email;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
public String getGender() {
return gender;
}
public Users build() throws Exception {
Users user=new Users(this);
if(user.getAge()>200) {
throw new Exception("参数格式不正确");
}
return user;
}
}
}
public class TestClass {
public static void main(String[] args) {
UsersBuilder ub=new UsersBuilder("张三","男");
Users user=null;
try {
user=ub.setAge(13).build();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(user.getEmail());
}
}