使用場(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ì)象。