應(yīng)用場(chǎng)景
1、對(duì)象的創(chuàng)建比較復(fù)雜司草,有順序限制或者組合依賴
2艰垂、構(gòu)建對(duì)象的參數(shù)比較多,并且包含較多可選參數(shù)
構(gòu)建實(shí)例
public class BillingtestClient {
private BillingtestClient() {
}
public static Builder builder() {
return new DefaultBuilder();
}
public interface Builder {
public Builder httpRequestConfig(HttpRequestConfig httpRequestConfig);
public BillingtestClient build() throws Exception;
}
private static class DefaultBuilder implements Builder {
private BillingtestClient billingtestClient;
public DefaultBuilder() {
billingtestClient = new BillingtestClient();
}
@Override
public Builder httpRequestConfig(HttpRequestConfig httpRequestConfig) {
billingtestClient.httpRequestConfig = httpRequestConfig;
return this;
}
@Override
public BillingtestClient build() throws Exception {
return billingtestClient;
}
}
}
解析
- 類(lèi)構(gòu)造器設(shè)置為私有
- 創(chuàng)建類(lèi)實(shí)例設(shè)置為public builder創(chuàng)建DefaultBuilder埋虹,DefaultBuilder實(shí)現(xiàn)了Builder接口猜憎,接口中定義需要設(shè)置的屬性值,以及最后的build返回設(shè)置完的類(lèi)實(shí)例