ビルダーパターンは不変オブジェクトを作成するのに人気がありますが、ビルダーを作成するにはプログラミングのオーバーヘッドがあります。だから、なぜ単純に構成オブジェクトを使用しないのだろうか。
ビルダーの使用法は次のようになります。
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);
この使用法にはさらに数行が必要ですが、非常に読みやすくなっていますが、実装ははるかに単純であり、ビルダーパターンに精通していない人にとっては理解しやすいかもしれません。ちなみに、このパターンの名前はありますか?
私が見落としていた構成アプローチの欠点はありますか?