作為java/Android開發者, 如果你想設計一個通用的庫, Builder模式幾乎肯定是會用到的, 我們需要提供良好的入口/接口來使用者可以彈性地構造他們需要的對象.
像一些優秀的開源庫, 例如Glide, OkHttp等都在構造Glide, OkHttpClient時用到Builder模式, 例如OkHttpClient的創建, 如下節選OkHttpClient.java的代碼:
public class OkHttpClient implements Cloneable, Call.Factory { public OkHttpClient() { this(new Builder()); } PRivate OkHttpClient(Builder builder) { this.dispatcher = builder.dispatcher; this.proxy = builder.proxy; this.protocols = builder.protocols; this.connectionSpecs = builder.connectionSpecs; this.interceptors = Util.immutableList(builder.interceptors); this.networkInterceptors = Util.immutableList(builder.networkInterceptors); this.proxySelector = builder.proxySelector; this.cookieJar = builder.cookieJar; this.cache = builder.cache; this.internalCache = builder.internalCache; this.socketFactory = builder.socketFactory; // more code... } public static final class Builder { public Builder() { ... } public Builder cache(Cache cache) { ... } public Builder dispatcher(Dispatcher dispatcher) { ... } public Builder protocols(List protocols) { ... } public List networkInterceptors() { ... } public Builder addNetworkInterceptor(Interceptor interceptor) { ... } public OkHttpClient build() { return new OkHttpClient(this); } }}Buidler模式, 是一種創建型的設計模式.
通常用來將一個復雜的對象的構造過程分離, 讓使用者可以根據需要選擇創建過程.另外, 當這個復雜的對象的構造包含很多可選參數時, 那Builder模式可以說是不二之選.
所以今天寫了一個Builer模式的一個demo
一個餃子的類 然后顧客根據自己的喜好自助添加作料
public class Dumpling { private boolean soy; private boolean vinegar; private boolean garlic; private boolean chili; public Dumpling(Builder builder) { this.soy = builder.soy; this.chili = builder.chili; this.garlic = builder.garlic; this.vinegar = builder.vinegar; } @Override public String toString() { StringBuilder builder = new StringBuilder("來一盤餃子放:"); if (this.soy){ builder.append("醬油"); } if (this.chili){ builder.append("辣椒"); } if (this.vinegar){ builder.append("醋"); } if (this.garlic){ builder.append("蒜"); } return builder.toString(); } public static class Builder { private boolean soy; private boolean vinegar; private boolean garlic; private boolean chili; public Builder() { } public Builder withSoy() { this.soy = true; return this; } public Builder withVinegar() { this.vinegar = true; return this; } public Builder withGarlic() { this.garlic = true; return this; } public Builder withChili() { this.chili = true; return this; } public Dumpling build() { return new Dumpling(this); } }一般來說Builder常常作為靜態內部類(提高內聚性)
下面是顧客自助活動
public class BuilderDemo { public static void main(String[] args) { Dumpling customer1 = new Dumpling.Builder() .withChili() .withGarlic() .withSoy() .build(); System.out.println("第一個顧客"+customer1.toString()); Dumpling customer2 = new Dumpling.Builder() .withSoy() .withVinegar() .build(); System.out.println("第二個顧客"+customer2.toString()); Dumpling customer3 = new Dumpling.Builder() .withVinegar() .withChili() .withGarlic() .build(); System.out.println("第三個顧客"+customer3.toString()); }}運行結果第一個顧客來一盤餃子放:醬油辣椒蒜第二個顧客來一盤餃子放:醬油醋第三個顧客來一盤餃子放:辣椒醋蒜
新聞熱點
疑難解答