Retrofit中的Builder模式
1、Retrofit的構(gòu)造
public final class Retrofit {
private final Map<Method, ServiceMethod> serviceMethodCache = new LinkedHashMap<>();
private final okhttp3.Call.Factory callFactory;
private final HttpUrl baseUrl;
private final List<Converter.Factory> converterFactories;
private final List<CallAdapter.Factory> adapterFactories;
private final Executor callbackExecutor;
private final boolean validateEagerly;
Retrofit(okhttp3.Call.Factory callFactory, HttpUrl baseUrl,
List<Converter.Factory> converterFactories, List<CallAdapter.Factory> adapterFactories,
Executor callbackExecutor, boolean validateEagerly) {
this.callFactory = callFactory;
this.baseUrl = baseUrl;
this.converterFactories = unmodifiableList(converterFactories); // Defensive copy at call site.
this.adapterFactories = unmodifiableList(adapterFactories); // Defensive copy at call site.
this.callbackExecutor = callbackExecutor;
this.validateEagerly = validateEagerly;
}
.......
public static final class Builder {
private Platform platform;
private okhttp3.Call.Factory callFactory;
private HttpUrl baseUrl;
private List<Converter.Factory> converterFactories = new ArrayList<>();
private List<CallAdapter.Factory> adapterFactories = new ArrayList<>();
private Executor callbackExecutor;
private boolean validateEagerly;
Builder(Platform platform) {
this.platform = platform;
// Add the built-in converter factory first. This prevents overriding its behavior but also
// ensures correct behavior when using converters that consume all types.
converterFactories.add(new BuiltInConverters());
}
public Builder() {
this(Platform.get());
}
......
public Retrofit build() {
......
return new Retrofit(callFactory, baseUrl, converterFactories, adapterFactories,
callbackExecutor, validateEagerly);
}
以上是Retrofit的構(gòu)造過程(其實(shí)在Builder構(gòu)造中也用到了簡(jiǎn)單工廠模式)。
2、Builder模式的特點(diǎn)
當(dāng)一個(gè)類有大量屬性需要初始化的時(shí)候,為了避免對(duì)外的API接口繁多和屬性建立的先后順序混亂,這個(gè)時(shí)候可以使用Builder模式來設(shè)置類的屬性,這樣可以把屬性和屬性的構(gòu)造過程完全分離,耦合性降低并且可擴(kuò)展性增加。
其實(shí)Retrofit中用了大量的Builder模式,再比如
ServiceMethod的構(gòu)造。
其實(shí)特點(diǎn)很好總結(jié):
- 外部類有個(gè)包含Builder參數(shù)的構(gòu)造函數(shù)
- 在構(gòu)造函數(shù)中把Builder中各個(gè)屬性的值賦給外部類中的對(duì)應(yīng)的屬性值
- 在Builder類中有一個(gè)builder方法,此方法返回值為外部類
- 為了客戶端鏈?zhǔn)秸{(diào)用設(shè)置Builder屬性值,把Builder中的方法返回值都設(shè)置為Builder(builder方法除外)
3、Builder模式的使用
在項(xiàng)目中用Builder模式封裝了WebView,因?yàn)閃ebView有大量的屬性需要構(gòu)造,把Builder模式用在這里是在合適不過了,Builder模式的運(yùn)用-WebView的構(gòu)造。