建造者模式常用于创建不可变对象,但创建一个建造者需要一些编程开销。所以我想知道为什么不直接使用配置对象。
使用建造者的示例代码如下:
Product p = Product.Builder.name("Vodka").alcohol(0.38).size(0.7).price(17.99).build();
显然,这很易读且简洁,但你需要实现构造器:
public class Product {
public final String name;
public final float alcohol;
public final float size;
public final float price;
private Product(Builder builder) {
this.name = builder.name;
this.alcohol = builder.alcohol;
this.size = builder.size;
this.price = builder.price;
}
public static class Builder {
private String name;
private float alcohol;
private float size;
private float price;
// mandatory
public static Builder name(String name) {
Builder b = new Builder();
b.name = name;
return b;
}
public Builder alcohol(float alcohol) {
this.alcohol = alcohol;
return.this;
}
public Builder size(float size) {
this.size = size;
return.this;
}
public Builder price(float price) {
this.price = price;
return.this;
}
public Product build() {
return new Product(this);
}
}
}
我的想法是,通过使用一个简单的配置对象来减少代码量,就像这样:
class ProductConfig {
public String name;
public float alcohol;
public float size;
public float price;
// name is still mandatory
public ProductConfig(String name) {
this.name = name;
}
}
public class Product {
public final String name;
public final float alcohol;
public final float size;
public final float price;
public Product(ProductConfig config) {
this.name = config.name;
this.alcohol = config.alcohol;
this.size = config.size;
this.price = config.price;
}
}
使用方法:
ProductConfig config = new ProductConfig("Vodka");
config.alcohol = 0.38;
config.size = 0.7;
config.price = 17.99;
Product p = new Product(config);
这种用法需要更多的代码行,但是同样非常易读。实现方式也更简单,对于不熟悉构建器模式的人来说可能更容易理解。顺便问一下:这种模式有名字吗?
我有没有忽略配置方法中的缺点?
Builder
中,您的 setter 需要return this;
才能使模式正常工作。 - rsp