前言
23種設(shè)計(jì)模式很多前輩或大神都分享過(guò)裆馒。為了加深對(duì)這些模式印象,我重新寫下來(lái)丐怯,用來(lái)記錄喷好。可以等以后读跷,重新查看梗搅,也能看出自己的進(jìn)步。如果發(fā)現(xiàn)有什么問(wèn)題效览?可以直接指出无切,謝謝!
構(gòu)建者模式的定義
將構(gòu)造過(guò)程跟表示過(guò)程進(jìn)行分離丐枉,使得同樣的構(gòu)建過(guò)程可以創(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等。
上面說(shuō)了那么多廢話族淮,還是直接上代碼辫红,因?yàn)槲以觳怀鰜?lái)了。祝辣。贴妻。本次代碼演示模擬支付
/**
* 創(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