作为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());
}
}
运行结果
第一个顾客来一盘饺子放:酱油辣椒蒜
第二个顾客来一盘饺子放:酱油醋
第三个顾客来一盘饺子放:辣椒醋蒜