如何为改造2创建单身人士? [英] How to make a singleton for retrofit 2?

查看:139
本文介绍了如何为改造2创建单身人士?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果存在多个改造调用,我怎样才能做出改进的单例,以便在类中不会重复代码,从而摆脱不必要的代码。

If there exists multiple retrofit call, how can i make a singleton of a retrofit, so that there won't be repeated codes within the class, thereby get rid of unnecessary codes.

推荐答案

下面是一个例子,但!虽然这可能很有光泽,易于使用,但单身人士是邪恶的。尽可能避免使用它们。一种解决方法是使用依赖注入。

Here's an example, but! Although this might be shiny and easy to use, singletons are evil. Try to avoid using them if possible. One way around it is by using dependency injection instead.

无论如何。

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;
    }
    ...
}

现在你拥有了一切在一个地方。使用它。

Now you have everything in one place. Use it.

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

这篇关于如何为改造2创建单身人士?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆