android - 如何为改造 2 制作单例?

标签 android singleton gson retrofit

如果存在多个retrofit调用,如何做一个retrofit的单例,这样类内就不会出现重复的代码,从而去除不必要的代码。

最佳答案

这是一个例子,但是!尽管这可能很 Shiny 且易于使用,但单例是邪恶的。尽可能避免使用它们。一种解决方法是改用依赖注入(inject)。

无论如何。

public class Api {
    private static Api instance = null;
    public static final String BASE_URL = "your_base_url";

    // Keep your services here, build them in buildRetrofit method later
    private UserService userService;

    public static Api getInstance() {
        if (instance == null) {
            instance = new Api();
        }

        return instance;
    }

    // Build retrofit once when creating a single instance
    private Api() {
        // Implement a method to build your retrofit
        buildRetrofit(BASE_URL);
    }

    private void buildRetrofit() {
        Retrofit retrofit = ...

        // Build your services once
        this.userService = retrofit.create(UserService.class);
        ...
    }

    public UserService getUserService() {
        return this.userService;
    }
    ...
}

现在您可以将所有内容集中在一个地方。使用它。

UserService userService = Api.getInstance().getUserService();

关于android - 如何为改造 2 制作单例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41672427/

相关文章:

kotlin - 我们可以依靠Gson修改val属性的能力吗?

java - 如何在jsonobject中设置数组

android - java.lang.NoClassDefFoundError : com. example.api.retrofit.AuthenticationInterceptor$拦截$1

c# - 类单例模式允许在 C# 中创建多个实例

java - 如何刷新单例类对象

java - 通过 EJB 共享静态单例

Android:将 Parcelable 转换为 JSON

android - Activity 上的 OnTouchListener 从不调用

java - 如何在 Firestore Firebase 中跳过初始数据并仅触发新更新?

android - 方形/ Dagger 。安卓。 java.lang.StackOverflowError 错误