建造者模式
建造者模式也是创建构建的一种方式,将复杂的对象进行抽象。主要解决在工厂模式和抽象工厂模式中创建的对象包含太多的参数问题。包含太多的参数的话会引起三个主要问题。
- 太多的参数传入工厂很容易出错,相同的类型传入工厂,客户端很难维护其顺序。
- 我们被迫传入所有参数,有些参数是可选的,传入不必要的可选参数时,需要被迫置为null。
- 如何对象创建复杂,工厂类的逻辑也会很复杂,容易让我们造成一些 困惑。
解决这些问题,我们可以提供一个具有必要参数的构造方法,然后用不同的setter来设置可选参数。但是这种方法的问题是,会造成对象不一致的问题,Builder模式解决了大量可选参数和不一致状态的问题,它提供了一种逐步构建对象的方法,并提供了一个实际返回最终object的方法。
设计步骤:
- 需要建立一个静态的内部类,并复制外部类的所有属性,并且遵循命名规范,如果类名是Phone,那么内部类的名字设为PhoneBuilder。
- 建造者类提供一个具有所有必要属性的构造方法。
- 建造者类为可选参数提供setter方法并返回当前建造者类对象。
- 最后建造者类提供一个build方法并返回客户端需要的对象。
代码示例:
public class Phone {
//必要的属性
private String model;
private String cpu;
//非必要属性
private double height;
private String widht;
public String getModel() {
return model;
}
public String getCpu() {
return cpu;
}
public double getHeight() {
return height;
}
public String getWidht() {
return widht;
}
private Phone(PhoneBuilder phoneBuilder){
this.cpu = phoneBuilder.cpu;
this.model = phoneBuilder.model;
this.height = phoneBuilder.height;
this.widht = phoneBuilder.widht;
}
public static class PhoneBuilder{
//必要的属性
private String model;
private String cpu;
//非必要属性
private double height;
private String widht;
public PhoneBuilder(String model, String cpu){
this.model = model;
this.cpu = cpu;
}
public PhoneBuilder setHeight(double height) {
this.height = height;
return this;
}
public PhoneBuilder setWidht(String widht) {
this.widht = widht;
return this;
}
public Phone build(){
return new Phone(this);
}
}
}
测试:
public class Demo {
public static void main(String[] args) {
Phone phone = new Phone.PhoneBuilder("华为mate60","遥遥领先").setHeight(180)
.setWidht("120").build();
}
}
翻译于:https://www.digitalocean.com/community/tutorials/builder-design-pattern-in-java