java customization builder_java – 改造界面的设计模式

长孙弘壮
2023-12-01

我的Retrofit界面创建器的设计有问题.我希望能够以通用方式实现API接口,并在传递令牌时更新相应的实例.目前,当我更新令牌时,我必须再次调用createService()方法来获取在生成接口时使用令牌的新实例…

有人问了类似的问题,但从来没有得到答案here

public class RetrofitCreator {

private static String TAG = "RetrofitCreator";

private static String WSSE = null;

private static String AmzToken = null;

static HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();

private static AmazonAPI amazonAPI = null;

private static VanishAPI cobaltAPI = null;

//static OkHttpClient client = new OkHttpClient.Builder().build();

static OkHttpClient.Builder httpClient = new OkHttpClient.Builder().addInterceptor(interceptor.setLevel(HttpLoggingInterceptor.Level.BODY));

private static Retrofit.Builder builder =

new Retrofit.Builder();

public static S createService(Class serviceClass) {

S mAPI = null;

if(serviceClass.getSimpleName().equals("VanishAPI")){

if(VanishAPI==null){

VanishAPI = (VanishAPI) createVanishAPI(serviceClass);

}

mAPI = (S) VanishAPI;

}else if(serviceClass.getSimpleName().equals("AmazonAPI")){

if(amazonAPI==null){

amazonAPI = (AmazonAPI) createAmazonAPI(serviceClass);

}

mAPI = (S) amazonAPI;

}

return mAPI;

}

public static void setWSSE(String WSSE) {

RetrofitCreator.WSSE = WSSE;

vanishAPI = createVanishAPI(VanishAPI.class);

}

public static void setAmzToken(String token) {

RetrofitCreator.AmzToken = token;

amazonAPI = createAmazonAPI(AmazonAPI.class);

}

private static S createAmazonAPI(Class serviceClass){

httpClient = getUnsafeOkHttpClient();

builder = new Retrofit.Builder()

.baseUrl(Constants.URL_AMAZON)

.addConverterFactory(JacksonConverterFactory.create());

if (AmzToken != null) {

Log.w(TAG, "WSSE not null!");

Interceptor interceptorSecure = new Interceptor() {

@Override

public Response intercept(Interceptor.Chain chain) throws IOException {

Request original = chain.request();

// Request customization: add request headers

Request.Builder requestBuilder = original.newBuilder()

.header("Cache-Control", "no-cache")

.header("Accept", "application/json")

.header("Authorization", "Bearer " + AmzToken)

.method(original.method(), original.body());

Request request = requestBuilder.build();

return chain.proceed(request);

}

};

httpClient.addInterceptor(interceptorSecure);

}

OkHttpClient client = httpClient.build();

Retrofit retrofit = builder.client(client).build();

return retrofit.create(serviceClass);

}

(...)

}

要在我使用的每个Activity中获取它:

amazonApi = RetrofitCreator.createService(AmazonAPI.class);

 类似资料: