如何重构此示例以避免在每种数据类型中检查isInstance的这种情况?我可以遵循任何模式吗?
public interface GenericData {}
public interface IntegerData extends GenericData{
public Integer Data();
}
public interface StringData extends GenericData{
public String Data();
}
public interface Client {
public boolean LoadData(GenericData data);
}
public class IntegerClientImpl implements Client{
public boolean LoadData(GenericData data){
return IntegerData.class.isInstance(data);
};
}
答案 0 :(得分:7)
您可以使用泛型
public interface Client<Data extends GenericData> {
public boolean LoadData(Data data);
}
public class IntegerClientImpl implements Client<IntegerData> {
@Override
public boolean LoadData(IntegerData data){
// ...
}
}