Java - DAO 不同类型的相同枚举

标签 java types enums dao

我正在尝试构建一个能够处理不同设置类型的 DAO。我想知道是否有一种巧妙的方法可以做到这一点而不会出现运行时错误。

public interface ChannelSettingDAO {
    Integer getIntegerSetting(ChannelSettingInteger channelSettingInteger);
    String getStringSetting(ChannelSettingString channelSettingString);
    Double getDoubleSetting(ChannelSettingDouble channelSettingDouble);
    void setIntegerSetting(ChannelSettingInteger channelSettingInteger, Integer value);
    void setStringSetting(ChannelSettingString channelSettingString, String value);
    void setDoubleSetting(ChannelSettingDouble channelSettingDouble, Double value);
}

public enum ChannelSettingInteger {
    CHANNEL_LOOKBACK(50);

    private Integer defaultValue;

    ChannelSettingInteger(Integer defaultValue) {
        this.defaultValue = defaultValue;
    }

    public Integer getDefaultValue() {
        return defaultValue;
    }
}

etc.. for every type of enum.

有没有更简洁的方法来做到这一点。我觉得我错过了一些东西,也许是某种为枚举提供类型的方法,或者是我错过了一些模式。

至少有一种方法可以强制 getDefault 名称相同。

有什么建议吗?

最佳答案

Is there any neater way to do this. I feel like I'm missing out on something, some way to give a type to an enum maybe, or some pattern I've missed out on. At least a way to enforce that the getDefault name is the same.

你是对的,你可以使用其他设计来更好地满足你的需求。
您可以引入一个接口(interface),每个枚举都必须实现该接口(interface)才能具有 getDefault() 方法。通过这种方式,您可以确保每个枚举都具有相同的基类型(接口(interface)中的哪一个),并且自在接口(interface)中声明以来就提供了 getDefault() 。 通过在接口(interface)上使用泛型类型,您允许每个枚举拥有自己的 getDefaultValue

数据类型

示例代码:

public interface IChannelSetting<T> {

    public T getDefaultValue();

}


public enum ChannelSettingInteger implements IChannelSetting<Integer> {

    CHANNEL_LOOKBACK(50);

    private Integer defaultValue;

    ChannelSettingInteger(Integer defaultValue) {
      this.defaultValue = defaultValue;
    }

    @Override
    public Integer getDefaultValue() {
      return defaultValue;
    }
}

我不知道您将如何使用您的 DAO,但仅出于您的个人信息,如果与您的需求相关,您可以进一步利用通用基础接口(interface),在您的应用程序中拥有对称逻辑和更少的代码道。

事实上,您可以在 DAO 中仅声明两个通用方法,例如:

public interface ChannelSettingDAO {
    <T> T getSetting(IChannelSetting<T> channelSetting);
    <T> void setSetting(IChannelSetting<T> channelSetting, T value);
}

关于Java - DAO 不同类型的相同枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38547426/

相关文章:

python - 如何在 Python 中实现以下 C 代码? (typedef、枚举和开关)

java - 将两个最多 50 位的整数相加

Excel VBA 集合和自定义数据类型

swift - 不同类(class)类型

.net - 在 F# 中强制任何对象为 null

vb.net - 从值获取VB.net枚举说明

java - Android: ListView 中的复选框(如何在适配器中创建OnCheckedChangeListener)

java - java中的一维数组到二维数组

java - 为什么有人会强制转换而不是返回子类型

c++ - 将枚举分配给变量时出错