目前我的方式是我有一个看起来像这样的ApiConfig类:
public class ApiConfig {
public enum Build{
RELEASE("https://api.endpoint.com"),
STAGE("http://api.stage.endpoint.com"),
DEV("http://api.dev.endpoint.com");
public String endpoint;
Build(String endpoint){
this.endpoint = endpoint;
}
}
}
我有一个ApiModule,它接受一个构建类型,所以我像这样实例化组件:
ApiComponent component = DaggerApiComponent.builder()
.apiModule(new ApiModule(ApiConfig.Build.DEV))
.build();
所以,现在如果我想更改端点,我将ApiConfig.Build.DEV更改为ApiConfig.Build.STAGE或ApiConfig.Build.RELEASE。这是正确的方法吗?最后,我希望能够按一个按钮在三者之间切换。
答案 0 :(得分:2)
这就是我的所作所为:
我有一个基于互联网示例的服务工厂类。请参阅下面的代码。
当我需要创建我的服务实例时,我打电话。
service = ServiceFactory.createRetrofitService(GithubService.class,
GithubService.SERVICE_ENDPOINT);
因此,如果将3个端点添加到GithubService接口。在所需视图的click事件中,只需使用所需的SERVICE_ENDPOINT调用ServiceFactory。
例如
public interface GithubService {
String RELEASE_ENDPOINT = "https://api.endpoint.com";
String STAGE_ENDPOINT = "http://api.stage.endpoint.com";
String DEV_ENDPOINT = "http://api.stage.endpoint.com";
@GET("/users/{login}")
Observable<UserResponse> getUser(@Path("login") String login);
}
在你的RELEASE按钮onClick()调用:
private GithubService service;
service = ServiceFactory.createRetrofitService(GithubService.class,
GithubService.SERVICE_ENDPOINT);
在你的STAGE按钮上onClick()调用:
private GithubService service;
service = ServiceFactory.createRetrofitService(GithubService.class,
GithubService.STAGE_ENDPOINT);
在您的DEV按钮onClick()中调用:
private GithubService service;
service = ServiceFactory.createRetrofitService(GithubService.class,
GithubService.DEV_ENDPOINT);
服务工厂代码:
public class ServiceFactory {
private static final String TAG = ServiceFactory.class.getSimpleName();
/**
* Creates a retrofit service from an arbitrary class (clazz)
* @param clazz Java interface of the retrofit service
* @param endPoint REST endpoint url
* @return retrofit service with defined endpoint
*/
public static <T> T createRetrofitService(final Class<T> clazz, final String endPoint) {
final RestAdapter restAdapter = new RestAdapter.Builder()
.setLogLevel(RestAdapter.LogLevel.FULL)
.setLog(new RestAdapter.Log() {
@Override
public void log(String message) {
Log.v(TAG, message);
}
})
.setEndpoint(endPoint)
.build();
T service = restAdapter.create(clazz);
return service;
}
}