何時需要建構器模式?
建構器模式提供了一種靈活且結構化的方法來建構複雜對象,特別是當它們的建構子可能有一個廣泛的參數列表。
常見範例應用程式:
相對於工廠模式的優點:
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中文網其他相關文章!