构建器模式是创建不可变对象的流行方法,但是创建构建器有一些编程开销。所以我想知道为什么不简单地使用config对象。
生成器的用法如下所示:
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);
这种用法需要多几行,但也很容易理解,但是实现起来要简单得多,对于不熟悉构建器模式的人来说,也许更容易理解。顺便说一句:这个模式有名称吗?
我忽略的配置方法是否有缺点?
构建器模式改善了去耦-您的产品可以是接口,并且唯一了解实现(某些情况下是实现)的类是构建器。如果构建器还实现了接口,则可以将其注入代码中以进一步增加去耦。
这种解耦意味着您的代码更易于维护且更易于测试。