我一直在尝试使用私有静态类来实现Bill Pugh Singleton设计模式来返回单例改造实例。到目前为止,我已经能够提出以下代码。有人可以帮助我查看这段代码并确认这是否是Bill Pugh先生自己建议的单身设计模式的正确实现,或者建议我采用正确的方法来实现这一点。
public class SingletonRetrofit {
private SingletonRetrofit(){}
private static class SingletonRetrofitHelper {
private static OkHttpClient okHttpClient;
private static Retrofit retrofit;
private static Retrofit makeRetrofit() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
okHttpClient = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.readTimeout(20, TimeUnit.SECONDS)
.connectTimeout(15, TimeUnit.SECONDS)
.build();
retrofit = new Retrofit.Builder()
.baseUrl("http://ci.draftserver.com/hornsbyapp/webservice/")
.client(okHttpClient)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit;
}
}
public static Retrofit getInstance() {
return SingletonRetrofitHelper.makeRetrofit();
}
}
答案 0 :(得分:-1)
使用这个:
public class Apiclient {
private static final String BASE_URL ="URL";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit == null) {
OkHttpClient.Builder httpClient2 = new OkHttpClient.Builder();
httpClient2.addNetworkInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request.Builder builder = chain.request().newBuilder();
builder.addHeader("site_id","1");
return chain.proceed(builder.build());
}
});
OkHttpClient client = httpClient2.build();
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}