Retrofit的设计模式 -- Builder模式

Retrofit中的Builder模式

1、Retrofit的构造

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的构造过程(其实在Builder构造中也用到了简单工厂模式)。
2、Builder模式的特点
当一个类有大量属性需要初始化的时候,为了避免对外的API接口繁多和属性建立的先后顺序混乱,这个时候可以使用Builder模式来设置类的属性,这样可以把属性和属性的构造过程完全分离,耦合性降低并且可扩展性增加。
其实Retrofit中用了大量的Builder模式,再比如
ServiceMethod的构造
其实特点很好总结:

  1. 外部类有个包含Builder参数的构造函数
  2. 在构造函数中把Builder中各个属性的值赋给外部类中的对应的属性值
  3. 在Builder类中有一个builder方法,此方法返回值为外部类
  4. 为了客户端链式调用设置Builder属性值,把Builder中的方法返回值都设置为Builder(builder方法除外)

3、Builder模式的使用
在项目中用Builder模式封装了WebView,因为WebView有大量的属性需要构造,把Builder模式用在这里是在合适不过了,Builder模式的运用-WebView的构造

推荐阅读更多精彩内容