如果存在多个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/