最适合使用的结构/模式?

时间:2013-10-31 16:51:14

标签: java enums

基本上我想要的是一个JComboBox,它有一个我已经添加到我的应用程序中的加密算法列表。当用户从JComboBox中选择一个时,所选算法将存储在变量中。

我对目前实现这一目标的设置并不满意......

我有一个接口算法如下:

public interface Algorithm {
    public String encrypt(String text, Object[] key);
    public String decrypt(String text, Object[] key);
}

然后我制作实现此接口的特定算法并覆盖这些方法,例如:

public class CaesarCipher implements Algorithm {

    @Override
    public String encrypt(String text, Object[] key) {
        ...
    }

    @Override
    public String decrypt(String text, Object[] key) {
        ...
    }      
}

现在在我的GUI中,我有一个变量和JComboBox,如下所示:

private Algorithm selectedAlgorithm;
private JComboBox algorithmsComboBox;

我希望JComboBox能够列出我已添加的所有不同算法,而且我也不知道这样做的正确方法...

所以我做了一个这样的枚举:

public enum AlgorithmType {

    CAESAR_CIPHER("Caesar Cipher", new CaesarCipher());

    private final String name;
    private final Algorithm algorithm;

    private AlgorithmType(String name, Algorithm algorithm) {
        this.name = name;
        this.algorithm = algorithm;
    }

    public Algorithm getAlgorithm() {
        return algorithm;
    }

    @Override
    public String toString() {
        return name;
    }

}

然后使用我的JComboBox,我做了类似的事情:

JComboBox<AlgorithmType> algorithmsComboBox = new JComboBox<AlgorithmType>(AlgorithmType.values());

我在我的JComboBox中添加了一个ActionListener,将selectedAlgorithm变量设置为所选的算法:

algorithmsComboBox.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
        selectedAlgorithm = ((AlgorithmType)algorithmComboBox.getSelectedItem()).getAlgorithm();
    }

});

这有效,但我不确定在枚举中存储这样的对象是否是一种好的做法,因为在枚举加载时不必要地创建所有对象。 有更好,更典型的方法吗?我可以想到一些替代方案,比如将每个算法存储在最终数组中,或者创建一个AlgorithmFactory?或者也许我不应该为每个算法创建单独的类,只有一个Algorithm类,它将AlgorithmType作为加密和解密方法的参数?

感谢。

2 个答案:

答案 0 :(得分:0)

我不建议在Enum中存储对象。相反,我建议制作一个键值对映射,并使用枚举作为键,算法作为值。有关具体信息,请查看AbstractMap.SimpleEntry<K,V>

答案 1 :(得分:0)

如果您正在寻找模式,请尝试Strategy,否则如果实现算法的对象在运行时没有更改,请尝试Template模式。

相关问题