1. 程式人生 > 其它 >設計模式-建造者設計模式(一)

設計模式-建造者設計模式(一)

為什麼要使用建造者設計模式

如果物件中屬性多,但是通常重要的只有幾個,因此建造者模式會讓開發者指定一些比較重要的屬性或者讓開發者指定某幾個物件型別,然後讓建造者去實現複雜的構建物件的過程,這就是物件的屬性與建立分離。這樣對於開發者而言隱藏了複雜的物件構建細節,降低了學習成本,同時提升了程式碼的可複用性

程式碼實現

public class BuilderTest {
    public static void main(String[] args) {
        Product product = new Product.Builder().productName("IPHONE手機").companyName("APPLE").build();
        System.out.println(product);
    }
}


class Product {
    private final String companyName;
    private final String productName;
    private final String color;
    private final String size;
    private final String money;

    Product(String companyName, String productName, String color, String size, String money) {
        this.companyName = companyName;
        this.productName = productName;
        this.color = color;
        this.size = size;
        this.money = money;
    }

    @Override
    public String toString() {
        return "Product{" +
                "companyName='" + companyName + '\'' +
                ", productName='" + productName + '\'' +
                ", color='" + color + '\'' +
                ", size='" + size + '\'' +
                ", money='" + money + '\'' +
                '}';
    }

    static class Builder {
        private String companyName;
        private String productName;
        private String color;
        private String size;
        private String money;

        Builder companyName(String companyName) {
            this.companyName = companyName;
            return this;
        }

        Builder productName(String productName) {
            this.productName = productName;
            return this;
        }

        Builder color(String color) {
            this.color = color;
            return this;
        }

        Builder size(String size) {
            this.size = size;
            return this;
        }

        Builder money(String money) {
            this.money = money;
            return this;
        }

        Product build() {
            return new Product(this.companyName, this.productName, this.color, this.size, this.money);
        }
    }
}