OkHttp uses a number of design patterns: singleton, Builder, factory, chain of responsibility, and observer

The singleton pattern

object ConnectInterceptor : Interceptor {
  ...
}
Copy the code

The builder module

open class OkHttpClient internal constructor(
  builder: Builder
) : Cloneable, Call.Factory, WebSocket.Factory {
  ...
  class Builder constructor() {... }}Copy the code

The factory pattern

interface Call : Cloneable {
  ...
 interface Factory {
    fun newCall(request: Request): Call
  } 
}
Copy the code

Chain of Responsibility model

fun getResponseWithInterceptorChain(): Response {
  val interceptors = mutableListOf<Interceptor>()
  interceptors += client.interceptors
  interceptors += RetryAndFollowUpInterceptor(client)
  interceptors += BridgeInterceptor(client.cookieJar)
  interceptors += CacheInterceptor(client.cache)
  interceptors += ConnectInterceptor
  if (!forWebSocket) {
    interceptors += client.networkInterceptors
  }
  interceptors += CallServerInterceptor(forWebSocket)
  val chain = RealInterceptorChain(interceptors, transmitter, null, 0, originalRequest, this,
    client.connectTimeoutMillis, client.readTimeoutMillis, client.writeTimeoutMillis)
  var calledNoMoreExchanges = false
  val response = chain.proceed(originalRequest)
  ...
}
Copy the code

Observer model

abstract class EventListener {
  ...
}
Copy the code