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

前言

23種設(shè)計(jì)模式很多前輩或大神都分享過。為了加深對(duì)這些模式印象,我重新寫下來,用來記錄??梢缘纫院?,重新查看,也能看出自己的進(jìn)步。如果發(fā)現(xiàn)有什么問題?可以直接指出,謝謝!

構(gòu)建者模式的定義

將構(gòu)造過程跟表示過程進(jìn)行分離,使得同樣的構(gòu)建過程可以創(chuàng)建不同的表示。

何時(shí)使用

創(chuàng)建一個(gè)復(fù)雜的對(duì)象,同時(shí)該復(fù)雜的對(duì)象有很多默認(rèn)不同的參數(shù);這個(gè)復(fù)雜對(duì)象各個(gè)部件激烈的變化,但是組合在一起卻相對(duì)穩(wěn)定。

使用場(chǎng)景

Java中的StringBuffer和StringBuilder類;Android的AlertDialog;很多第三方框架中也會(huì)使用到,如聚合支付SDK(Ping++)、nohttp等。

上面說了那么多廢話,還是直接上代碼,因?yàn)槲以觳怀鰜砹恕?。。本次代碼演示模擬支付

/**
 * 創(chuàng)建者模式
 */
public class Payment {

    private Builder builder;

    private Payment(Builder builder) {
        this.builder = builder;
    }

    public void pay() {
        System.out.println("發(fā)起支付");
        System.out.println("支付中...");
        System.out.println("支付信息:" + this.builder.toString());
        System.out.println("支付成功");
    }


    public static class Builder {

        int id;

        String orderNo;

        String callBackUrl;

        String price;

        String body;

        public Builder() {
            this.id = new Random().nextInt(1000);
            this.orderNo = String.valueOf(System.currentTimeMillis());
            this.callBackUrl = "https:www.baidu.com";
            this.price = String.valueOf(new Random().nextInt(100000));
        }


        public Builder setId(int id) {
            this.id = id;
            return this;
        }

        public Builder setOrderNo(String orderNo) {
            this.orderNo = orderNo;
            return this;
        }

        public Builder setCallBackUrl(String callBackUrl) {
            this.callBackUrl = callBackUrl;
            return this;
        }

        public Builder setPrice(String price) {
            this.price = price;
            return this;
        }

        public Builder setBody(String body) {
            this.body = body;
            return this;
        }

        public Payment create() {
            return new Payment(this);
        }

        public String toString() {
            return "\n" + "id=" + id + "\n" + "orderNo=" + orderNo + "\n" +
                    "callBackUrl=" + callBackUrl + "\n" + "price=" + price + "\n" + "body=" + body;
        }

    }
}

測(cè)試代碼:

public class MainTest {
    public static void main(String[] args) {
        new Payment.Builder().setBody("2018,加油").create().pay();
    }
}

輸出結(jié)果:

發(fā)起支付
支付中...
支付信息:
id=243
orderNo=1515083956958
callBackUrl=https:www.baidu.com
price=15259
body=2018,加油
支付成功

參考資料:
http://blog.csdn.net/qq_23901559/article/details/49368793
http://www.runoob.com/design-pattern/builder-pattern.html

?著作權(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)容