上篇博客简单地介绍了一下builder设计模式,其实也很简单,相信聪明的你能很快理解他的精髓,这篇就来说说okhttp3的设计模式,其实也是builder模式,只不过和alertdialog有点小小的区别,这个区别就是在成员变量位置,ok3没有对成员变量进行封装,而alertdialog将成员变量封装到了一个含有内部类的类中了;
下面先看下ok3的代码:
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(5, TimeUnit.SECONDS)
.cache(null)
.build();
okHttpClient.newCall(null).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
}
});
1 okhttpclient类的结构
大致分为三部分,成员变量(okhttpclient),内部类(builder)和内部类的的区部变量(builder)三部分;这里我就简单地写下:(看源码不要走进一个误区,非要看懂每一行代码的话那你就比高司令还厉害了,能看懂70%你就了不得了)
public class OkHttpClient{
//变量太多就不全部粘贴出来了
final boolean followRedirects;
final boolean retryOnConnectionFailure;
final int connectTimeout;
final int readTimeout;
final int writeTimeout;
final int pingInterval;
//各种get和set方法,此处省略一万字,你懂得
OkHttpClient(Builder builder) {
this.followRedirects = builder.followRedirects;
this.retryOnConnectionFailure = builder.retryOnConnectionFailure;
this.connectTimeout = builder.connectTimeout;
this.readTimeout = builder.readTimeout;
this.writeTimeout = builder.writeTimeout;
this.pingInterval = builder.pingInterval;
}
//内部类builder
public static final class Builder {
boolean followRedirects;
boolean retryOnConnectionFailure;
int connectTimeout;
int readTimeout;
int writeTimeout;
int pingInterval;
public Builder() {
followSslRedirects = true;
followRedirects = true;
retryOnConnectionFailure = true;
connectTimeout = 10_000;
readTimeout = 10_000;
writeTimeout = 10_000;
pingInterval = 0;
}
public Builder connectionPool(ConnectionPool connectionPool) {
if (connectionPool == null) throw new NullPointerException("connectionPool == null");
this.connectionPool = connectionPool;
return this;
}
//类似方法省略
public OkHttpClient build() {
return new OkHttpClient(this);//这里直接将builder对象传入构造中,在okhttpclient的构造方法中将builder的变量取出赋值给okhttpclient的成员变量
}
}
}
}
2 newcall方法
/** 源码里面是这样的, * Prepares the {@code request} to be executed at some point in the future. */
@Override public Call newCall(Request request) {
return new RealCall(this, request, false /* for web socket */);
}
//后面调用这个方法,他是而这个方法里面的关键就是AsyncCall,进行请求
@Override public void enqueue(Callback responseCallback) {
synchronized (this) {
if (executed) throw new IllegalStateException("Already Executed");
executed = true;
}
captureCallStackTrace();
client.dispatcher().enqueue(new AsyncCall(responseCallback));
}
我们再来看看Callback是干嘛的:
void onFailure(Call call, IOException e);
void onResponse(Call call, Response response) throws IOException;
原来是一个回调接口;
2 request
Request request = new Request.Builder()
.get()
.build();
也是一个builder模式;