避免 isInstance 语句
Avoiding isInstance statement
我如何重构这个例子来避免我需要在每种数据类型中检查 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);
};
}
您可以使用泛型
public interface Client<Data extends GenericData> {
public boolean LoadData(Data data);
}
public class IntegerClientImpl implements Client<IntegerData> {
@Override
public boolean LoadData(IntegerData data){
// ...
}
}
我如何重构这个例子来避免我需要在每种数据类型中检查 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);
};
}
您可以使用泛型
public interface Client<Data extends GenericData> {
public boolean LoadData(Data data);
}
public class IntegerClientImpl implements Client<IntegerData> {
@Override
public boolean LoadData(IntegerData data){
// ...
}
}