概述
java23種設計模式之一,英文叫Builder Pattern。其核心思想是將一個“複雜對象的構建算法”與它的“部件及組裝方式”分離,使得構件算法和組裝方式可以獨立應對變化;復用同樣的構建算法可以創建不同的表示,不同的構建過程可以復用相同的部件組裝方式。
代碼示例
// Person
public classPerson {
privateString head;
privateString body;
privateString foot;
publicString getHead() {
return head;
}
public voidsetHead(String head) {
this.head= head;
}
publicString getBody() {
return body;
}
publicString getFoot() {
return foot;
}
public voidsetFoot(String foot) {
this.foot= foot;
}
public voidsetBody(String body) {
this.body= body;
}
}
//Builder接口
public interfacePersonBuilder{
voidbuildHead();
voidbuildBody();
voidbuildFoot();
Person buildPerson();
}
//Builder實現:人類
public classHumanBuilder implementsPersonBuilder {
privatePerson person;
publicHumanBuilder(){
this.person=newPerson();
}
public voidbuildBody() {
this.person.setBody("創建 人類 身體!");
}
public voidbuildFoot() {
this.person.setFoot("創建 人類 腳!");
}
public voidbuildHead() {
this.person.setHead("創建 人類 頭!");
}
publicPerson buildPerson() {
return person;
}
}
//Builder實現:變形金剛
public classtransformerBuilder implementsPersonBuilder {
privatePerson person;
publicTransformerBuilder(){
this.person=newPerson();
}
public voidbuildBody() {
this.person.setBody("創建 變形金剛 身體!");
}
public voidbuildFoot() {
this.person.setFoot("創建 變形金剛 腳!");
}
public voidbuildHead() {
this.person.setHead("創建 變形金剛 頭!");
}
publicPerson buildPerson() {
return person;
}
}
//Director構建嚮導
public classPersonDirector {
publicPerson constructPerson(PersonBuilder pb) {
pb.buildHead();
pb.buildBody();
pb.buildFoot();
returnpb.buildPerson();
}
}
//測試
public classTest {
public static voidmain(String[] ARGs) {
PersonDirector pd = newPersonDirector();
Person person = pd.constructPerson(newHumanBuilder());
System.out.println(person.getBody());
System.out.println(person.getFoot());
System.out.println(person.getHead() +" \n");
Person transformer = pd.constructPerson(newTransformerBuilder());
System.out.println(transformer.getBody());
System.out.println(transformer.getFoot());
System.out.println(transformer.getHead());
}
}