问题:多个属性的对象创建
- 解决方案1:重载多个构造器,但是随着属性的增加,构造器个数也会成吨的增长,且要选择正确的构造器难度增添了不少。
public class Computer {
private String cpu; //可选,默认为intel
private String motherboard ; //,可选,默认为gigabyte
private String memory;
private String graphics;
public Computer(String cpu, String motherboard, String memory, String graphics) {
this.cpu = cpu;
this.motherboard = motherboard;
this.memory = memory;
this.graphics = graphics;
}
public Computer(String motherboard, String memory, String graphics) {
this("intel", motherboard, memory, graphics);
}
public Computer(String memory, String graphics) {
this("intel", "gigabyte", memory, graphics);
}
...
}
- 解决方案2:通过setter注入,但是setter注入也会随着属性增加而要写的代码线性增长
public class Computer {
private String cpu = "intel"; //可选,默认为intel
private String motherboard = "gigabyte"; //,可选,默认为gigabyte
private String memory;
private String graphics;
public void setCpu(String cpu) {
this.cpu = cpu;
}
public void setMotherboard(String motherboard) {
this.motherboard = motherboard;
}
public void setMemory(String memory) {
this.memory = memory;
}
public void setGraphics(String graphics) {
this.graphics = graphics;
}
}
构建者模式
public class ComputerFacts {
private String cpu; //可选,默认为intel
private String motherboard ; //,可选,默认为gigabyte
private String memory;
private String graphics;
public static class Builder{
private String cpu = "intel"; //可选,默认为intel
private String motherboard = "gigabyte" ; //,可选,默认为gigabyte
private String memory;
private String graphics;
public Builder cpu(String cpu) {
this.cpu = cpu;
return this;
}
public Builder motherboard(String motherboard) {
this.motherboard = motherboard;
return this;
}
public Builder memory(String memory) {
this.memory = memory;
return this;
}
public Builder graphics(String graphics) {
this.graphics = graphics;
return this;
}
public ComputerFacts build(){
return new ComputerFacts(this);
}
}
private ComputerFacts(Builder builder){
this.cpu = builder.cpu;
this.motherboard = builder.motherboard;
this.memory = builder.memory;
this.graphics = builder.graphics;
}
}
//客户端调用
ComputerFacts computer = new ComputerFacts.Builder()
.graphics("geforce")
.memory("kingstom")
.build();
相对前面的第一种可以避免要花时间去选择合适的构造器,对于第二种不用一个一个属性进行注入。但是缺点也明显,就是这个模式的代码量明显多了很多,且构建一个对象调用了两次new方法,效率相对较低。如果是多个参数的对象,为了使得客户端代码更容易编写,更倾向于使用这种模式来创建对象。