設(shè)計(jì)模式之建造者模式

使用場(chǎng)景

  • 對(duì)象的構(gòu)建有很多必填參數(shù),如果使用構(gòu)造函數(shù)會(huì)導(dǎo)致參數(shù)列表過長(zhǎng)難以使用
  • 構(gòu)造參數(shù)之間有依賴關(guān)系,比如設(shè)置了minAge就必須設(shè)置maxAge,且minAge小于等于maxAge
  • 類的屬性一旦被創(chuàng)建就不可變(不暴力set()方法)

類圖

image.png

Person類包含了一個(gè)內(nèi)部類Builder,負(fù)責(zé)對(duì)外暴露設(shè)置屬性的方法,這些方法可以包含校驗(yàn)和初始化規(guī)則,屬性之前的依賴規(guī)則可以放到最終調(diào)用的build()方法中校驗(yàn)

代碼實(shí)現(xiàn)

public class Person {

    private Long id;
    private String name;
    private Integer minAge;
    private Integer maxAge;

    private Person() {
    }

    public static class Builder {

        private Person person = new Person();

        public Builder id(Long id) {
            person.id = id;
            return this;
        }

        public Builder name(String name) {
            person.name = name;
            return this;
        }

        public Builder minAge(Integer minAge) {
            person.minAge = minAge;
            return this;
        }

        public Builder maxAge(Integer maxAge) {
            person.maxAge = maxAge;
            return this;
        }

        public Person build() {
            if (person.minAge != null && person.maxAge != null) {
                if (person.minAge < 0) {
                    throw new IllegalArgumentException("minAge必須大于等于0");
                }
                if (person.maxAge <= person.minAge) {
                    throw new IllegalArgumentException("maxAge必須大于等于minAge");
                }
            } else if ((person.minAge == null && person.maxAge != null) ||
                    (person.minAge != null && person.maxAge == null)) {
                throw new IllegalArgumentException("minAge和maxAge必須同時(shí)設(shè)置");
            }
            return person;
        }

    }

}

與工廠模式有何區(qū)別?

  • 工廠模式是用來創(chuàng)建不同但是相關(guān)類型的對(duì)象(繼承同一父類或者接口的一組子類),由給定的參數(shù)來決定創(chuàng)建哪種類型的對(duì)象。
  • 建造者模式是用來創(chuàng)建一種類型的復(fù)雜對(duì)象,通過設(shè)置不同的可選參數(shù),“定制化”地創(chuàng)建不同的對(duì)象。
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容