我有以下界面:
public interface ProvidersFilter {
void setQuery(@NonNull Object query);
Object apply();
}
以下实施类:
首次实施:
public class ProvidersRemoteFilter implements ProvidersFilter {
private Query mQuery;
@Override
public void setQuery(@NonNull Object query) {
if (query instanceof Query) {
mQuery = (Query) query;
} else {
throw new RuntimeException("query object must be of type com.google.firebase.firestore.Query");
}
}
@Override
public Object apply() {
return mQuery;
}
}
第二次实施:
public class ProvidersLocalFilter implements ProvidersFilter {
private String mQuery;
@Override
public void setQuery(@NonNull Object query) {
if (query instanceof String) {
mQuery = (String) query;
} else {
throw new RuntimeException("query object must be of type String");
}
}
@Override
public Object apply() {
return mQuery;
}
}
我希望通过生成我的界面和实现类来避免使用instanceof
。
答案 0 :(得分:4)
您需要在界面中添加一个类型变量。
接口:
public interface ProvidersFilter<T> {
void setQuery(@NonNull T query);
T apply();
}
实施班级:
public class ProvidersRemoteFilter implements ProvidersFilter<Query> {
private Query mQuery;
@Override
public void setQuery(@NonNull Query query) {
mQuery = query;
}
@Override
public Query apply() {
return mQuery;
}
}
答案 1 :(得分:0)
由于本地和远程提供程序具有相同的代码,因此您可以使用实现共性的抽象类。在这种情况下,不需要界面,但你可以保持相同:
public interface ProvidersFilter<Q> {
void setQuery(@NonNull Q query);
Q apply();
}
abstract class AbstractProvidersFilter<Q> {
private Q mQuery;
@Override
public void setQuery(@NonNull Q query) {
mQuery = query;
}
@Override
public Q apply() {
return mQuery;
}
}
public class ProvidersRemoteFilter extends AbstractProvidersFilter<Query> {}
public class ProvidersLocalFilter extends AbstractProvidersFilter<String> {}