介紹
該模式為了將構(gòu)建復(fù)雜對(duì)象的過(guò)程和他的部件解耦逆粹,使得構(gòu)建構(gòu)成和部件的表示隔離開(kāi)。
UML
上代碼
package com.ralap.builder;
/**
* Created by ralap on 2017/9/27.
*/
public class Computers {
private final String mCpu;
private final String mDisplay;
private final String mOs;
private Computers(Builder builder) {
this.mCpu = builder.cpu;
this.mDisplay = builder.display;
this.mOs = builder.os;
}
public static class Builder {
private final String cpu;
private String display;
private String os;
public Builder(String cpu) {
this.cpu = cpu;
}
public Builder display(String display) {
this.display = display;
return this;
}
public Builder os(String os) {
this.os = os;
return this;
}
public Computers create() {
return new Computers(this);
}
}
public String getmCpu() {
return mCpu;
}
public String getmDisplay() {
return mDisplay;
}
public String getmOs() {
return mOs;
}
}
說(shuō)明
- Computers構(gòu)造私有;
- 不可變參數(shù)使用final表蝙,防止后續(xù)修改寒锚;
- Bullder的設(shè)置參數(shù)使用鏈?zhǔn)?/li>
優(yōu)缺點(diǎn):
- 優(yōu)點(diǎn):
- 良好的封裝性劫映,使用構(gòu)建者模式可以是客戶端不必知道看平內(nèi)部的組成細(xì)節(jié);
- 構(gòu)建者獨(dú)立刹前,容易擴(kuò)展泳赋;
- 缺點(diǎn)
- 會(huì)產(chǎn)生多余的Builder對(duì)象,消耗內(nèi)存喇喉;