如果存在多个改装调用,我如何进行改造的单例,以便在类中不会重复代码,从而摆脱不必要的代码.
这是一个例子,但是!虽然这可能是闪亮的,易于使用,但单身人士是邪恶的.尽可能避免使用它们.解决它的一种方法是使用依赖注入.
无论如何.
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();