文章目录
builder就是将复杂对象的构建与表示分离
kotlin版本实现
//会省略很多代码
open class OkhttpClient internal contrustor(builder:Builder){
@get: JvmName("dispatcher")val dispatcher: Dispatcher = builder.dispatcher
@get: JvmName("connectionPool") val connectionPool: ConnectionPool = builder.connectionPool
// 省略很多属性
constructor():this(Builder())
init{
//会省略很多代码
}
class Builder constructor(){
internal val dispatcher: Dispatcher = dispatcher()
internal var connectionPool: ConnectionPool = connectionPool()
//省略很多属性
internal constructor(okhttpClient: OkhttpClient):this(){
this.dispatcher = okHttpClient.dispatcher
this.connectionPool = okHttpClient.connectionPool
//省略很多属性
}
fun dispatcher(dispatcher: Dispatcher) = apply{
this.dispatcher = dispatcher
}
fun connectionPool(connectionPool: ConnectionPool) = apply{
this.connectionPopl = connectionPool
}
//省略很多属性
fun build():OkhttpClient = OkhttpClient(this)
}
}
java版本
public class OkHttpClient{
final Dispatcher dispatcher;
final ConnectionPool connectionPool;
//省略很多属性
public OkHttpClient() {
this(new Builder());
}
public OkhttpClient(Builder builder){
this.dispatcher = builder.dispatcher;
this.connectionPool = builder.connectionPool;
//省略很多属性
}
public Dispatcher dispatcher(){
return dispatcher;
}
public ConnectionPool connectionPool() {
return connectionPool;
}
public static final class Builder{
Dispatcher dispatcher;
ConnectionPool connectionPool;
public Builder(){
<!--省略很多代码-->
}
Builder(OkHttpClient okHttpClient) {
<!--省略很多代码-->
}
public Builder dispatcher(Dispatcher dispatcher){
this.dispatcher = dispatcher;
return this;
}
public Buidler connectionPool(ConnectionPool connectionPool){
this.connection
}
public OkHttpClient build() {
return new OkHttpClient(this);
}
}
}
}