何时需要构建器模式?
构建器模式提供了一种灵活且结构化的方法来构造复杂对象,特别是当它们的构造函数可能有一个广泛的参数列表。
常见示例应用程序:
相对于工厂模式的优点:
Java 中的示例实现:
public class Pizza { private int size; private boolean cheese; private boolean pepperoni; private boolean bacon; private Pizza(Builder builder) { this.size = builder.size; this.cheese = builder.cheese; this.pepperoni = builder.pepperoni; this.bacon = builder.bacon; } public static class Builder { // Required private final int size; // Optional private boolean cheese = false; private boolean pepperoni = false; private boolean bacon = false; public Builder(int size) { this.size = size; } public Builder cheese(boolean value) { this.cheese = value; return this; } public Builder pepperoni(boolean value) { this.pepperoni = value; return this; } public Builder bacon(boolean value) { this.bacon = value; return this; } public Pizza build() { return new Pizza(this); } } }
此构建器允许灵活且一致的披萨配置:
Pizza pizza = new Pizza.Builder(12) .cheese(true) .pepperoni(true) .bacon(false) .build();
以上是什么时候应该使用构建器模式来构建对象?的详细内容。更多信息请关注PHP中文网其他相关文章!