设计模式-建造者设计模式(一)
作者:互联网
为什么要使用建造者设计模式
如果对象中属性多,但是通常重要的只有几个,因此建造者模式会让开发者指定一些比较重要的属性或者让开发者指定某几个对象类型,然后让建造者去实现复杂的构建对象的过程,这就是对象的属性与创建分离。这样对于开发者而言隐藏了复杂的对象构建细节,降低了学习成本,同时提升了代码的可复用性
代码实现
public class BuilderTest {
public static void main(String[] args) {
Product product = new Product.Builder().productName("IPHONE手机").companyName("APPLE").build();
System.out.println(product);
}
}
class Product {
private final String companyName;
private final String productName;
private final String color;
private final String size;
private final String money;
Product(String companyName, String productName, String color, String size, String money) {
this.companyName = companyName;
this.productName = productName;
this.color = color;
this.size = size;
this.money = money;
}
@Override
public String toString() {
return "Product{" +
"companyName='" + companyName + '\'' +
", productName='" + productName + '\'' +
", color='" + color + '\'' +
", size='" + size + '\'' +
", money='" + money + '\'' +
'}';
}
static class Builder {
private String companyName;
private String productName;
private String color;
private String size;
private String money;
Builder companyName(String companyName) {
this.companyName = companyName;
return this;
}
Builder productName(String productName) {
this.productName = productName;
return this;
}
Builder color(String color) {
this.color = color;
return this;
}
Builder size(String size) {
this.size = size;
return this;
}
Builder money(String money) {
this.money = money;
return this;
}
Product build() {
return new Product(this.companyName, this.productName, this.color, this.size, this.money);
}
}
}
标签:String,companyName,color,money,建造,productName,设计模式,size 来源: https://www.cnblogs.com/zhu12/p/14944835.html