针对构建一个对象时,该对象有多个属性,构建比较复杂,容易出错 ,且如果直接用构造方法构建的话,为了保证多种需求,有的参数不需要传,有的需要传,一共有10个属性,你需要无参构造、一个参数的构造方法、两个参数的构造方法...一堆构造方法。
为了解决这个问题,可以使用建造者模式。
package creational.builder;
public class Person {
int id;
String name;
int age;
double weight;
int score;
Location loc;
private Person() {}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", weight=" + weight +
", score=" + score +
", loc=" + loc +
'}';
}
public static class PersonBuilder {
Person p = new Person();
public PersonBuilder basicInfo(int id, String name, int age) {
p.id = id;
p.name = name;
p.age = age;
return this;
}
public PersonBuilder weight(double weight) {
p.weight = weight;
return this;
}
public PersonBuilder score(int score) {
p.score = score;
return this;
}
public PersonBuilder loc(String street, String roomNo) {
p.loc = new Location(street, roomNo);
return this;
}
public Person build() {
return p;
}
}
}
package creational.builder;
public class Main {
public static void main(String[] args) {
Person p = new Person.PersonBuilder()
.basicInfo(1, "zhangsan", 18)
//.score(20)
.weight(200)
//.loc("bj", "23")
.build();
System.out.println(p.toString());
}
}
以上代码可以看到,先基于Bulider对象进行初始化赋值完善,完成后,调用build()方法,得到最终的要构建的对象。