Okhttp中 kotlin和java 实现Builder模式

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);
        }
    }


        
 }
  
  
    
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值