java—在应用程序类中使用静态接口安全吗?

rdlzhqv9  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(351)

使用这些类有问题吗?这个静态接口以后会不会给应用程序类带来任何问题?

public class App extends Application {
private static KareezAPI apiService;
private InternetConnectionListener mInternetConnectionListener;
public static final int DISK_CACHE_SIZE = 10 * 1024 * 1024; // 10 MB
public void setInternetConnectionListener(InternetConnectionListener listener) {
    mInternetConnectionListener = listener;
}

public void removeInternetConnectionListener() {
    mInternetConnectionListener = null;
}

public KareezAPI getApiService(Activity activity) {
    if (apiService == null) {
        apiService = provideRetrofit(KareezAPI.BASE_URL,activity).create(KareezAPI.class);
        }
    return apiService;
}
                                   }

这是接口:

public interface KareezAPI{
String BASE_URL="https://baseurl.heroapp.com/";
@POST("register")
Call<RegisterResponse> RegisterUser( @Body RegisterData registerData);

@POST("login")
Call<RegisterResponse> LoginUser(@Body LoginData loginData); public interface LoginUserCallback{
    public void onResponse(Call<RegisterResponse> call, Response<RegisterResponse> response);
    public void onFailure(Call<RegisterResponse> call, Throwable t);
}

}

这就是这个接口和app类的用法

((App) activity.getApplication()).getApiService(activity).LoginUser(loginData).enqueue(new 
                                               Callback<RegisterResponse>() {
        @Override
        public void onResponse(@NonNull Call<RegisterResponse> call, @NonNull 
             Response<RegisterResponse> response) {
            loginUserCallback.onResponse(call, response);
        }

        @Override
        public void onFailure(@NonNull Call<RegisterResponse> call, Throwable t) {
            loginUserCallback.onFailure(call, t);
        }
    });
xzabzqsa

xzabzqsa1#

对我来说,将api逻辑添加到应用程序类是没有意义的。你能做的就是在你的房间里使用改装 KareezAPI 接口,并编写如下内容:

Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

KareezAPI service = retrofit.create(KareezAPI.class);

然后,当你想用的时候,写下来

KareezAPI.service.LoginUser().enqueue()...

你想去哪都行。

相关问题