我需要在运行时选择LocationProvider
的正确实现。都
GoogleLocationService
和AndroidLocationService
有它们自己的依存关系。
public interface LocationProvider{
Observable<Location> getLocationProvider(Looper looper);
}
@ActivityScope
public class GoogleLocationService implements LocationProvider{
...
@Inject
public GoogleLocationService (...){
}
}
@ActivityScope
public class AndroidLocationService implements LocationProvider{
...
@Inject
public AndroidLocationService (...){
}
}
@ActivityScope
public class LocationControl{
LocationProvider locationProvider;
@Inject
public LocationControl(...){
...
}
public void start(){
if(isGooglePlayServiceAvailable){
locationProvider = new GoogleLocationService(...);
} else {
locationProvider = new AndroidLocationService(...);
}
}
}
使用Dagger 2满足这些依赖性的最佳方法是什么? 我应该使用懒惰注射吗?
@ActivityScope
public class LocationControl{
@Inject
Lazy<AndroidLocationService> androidlocationService;
@Inject
Lazy<GoogleLocationService> googlelocationService;
LocationProvider locationProvider;
@Inject
public LocationControl(...){
...
}
public void start(){
if(isGooglePlayServiceAvailable){
locationProvider = googlelocationService.get();
} else {
locationProvider = androidLocationService.get();
}
}
}
还是工厂?
@ActivityScope
public class LocationControl{
private final LocationProviderFactory locationProviderFactory;
LocationProvider locationProvider;
@Inject
public LocationControl(LocationProviderFactory locationProviderFactory){
this.locationProviderFactory = locationProviderFactory;
}
public void start(){
if(isGooglePlayServiceAvailable){
locationProvider = locationProviderFactory.getLocationProvider(google);
} else {
locationProvider = locationProviderFactory.getLocationProvider(android);
}
}
}
@ActivityScope
public class LocationProviderFactory{
private final GoogleLocationService GoogleLocationService;
private final AndroidLocationService AndroidLocationService;
@Inject
public LocationProviderFactory(GoogleLocationService googleLocationService, AndroidLocationService androidLocationService){
this.googleLocationService = googleLocationService;
this.androidLocationService = androidLocationService;
}
public LocationProvider getLocationProvider(condition){
if(condition){
return googleLocationService;
} else {
return androidLocationService;
}
}
}
或者也许有更好的方法?