我还是新单身人士。我试图使用DRY方法,但我不确定它是否正确。下面是我用来创建OkHttpClient和Retrofit.Builder的类Authorization。我不确定它是否正确:
public class Authorization {
private static Retrofit retrofit = null;
public static Retrofit authorize(Activity activity){
final String token = SharedPreferencesMethods.getFromSharedPreferences(activity, activity.getString(R.string.token));
OkHttpClient client = new OkHttpClient();
client.interceptors().add(new Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
Request newRequest =
chain.request().newBuilder()
.addHeader("Authorization", "Bearer " + token).build();
return chain.proceed(newRequest);
}
});
if(retrofit == null){
retrofit = new Retrofit.Builder()
//10.0.3.2 for localhost
.baseUrl("http://teamh-spring.herokuapp.com")
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
方法授权的返回值是返回一个改进对象。 它是单身吗?
这里我称之为api
CirkelsessieAPI cirkelsessieAPI = Authorization.authorize(getActivity()).create(CirkelsessieAPI.class);
Call<List<Cirkelsessie>> call = cirkelsessieAPI.getCirkelsessies();
// more code here
谢谢!
答案 0 :(得分:0)
不,不是。 单例是一种设计模式,它将类的实例限制为一个对象。我相信你可以看到为什么你可以实例化多个Authorization对象,而类“Authorization”将类Retrofit的实例限制为一个对象的属性,它不能以任何方式限制其他人实例化其他地方的另一个改造对象。