避免使用isInstance语句

时间:2016-04-04 11:59:17

标签: java design-patterns isinstance

如何重构此示例以避免在每种数据类型中检查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);
    };
}

1 个答案:

答案 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){
        // ...
    }
}