Java 用于此目的的最佳结构/模式?

Java 用于此目的的最佳结构/模式?,java,enums,Java,Enums,基本上,我想要的是一个JComboBox,其中包含我添加到应用程序中的加密算法列表。当用户从JComboBox中选择一个算法时,所选算法存储在一个变量中 我不是真的很满意我目前的设置来实现这一点 我有一个接口算法如下: public interface Algorithm { public String encrypt(String text, Object[] key); public String decrypt(String text, Object[] key); }

基本上,我想要的是一个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<AlgorithmType> algorithmsComboBox = new JComboBox<AlgorithmType>(AlgorithmType.values());
然后,为了使用我的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<AlgorithmType> algorithmsComboBox = new JComboBox<AlgorithmType>(AlgorithmType.values());
这是可行的,但我不确定在枚举中存储这样的对象是否是一种好的做法,因为所有对象都是在加载枚举时不必要地创建的。 有没有更好、更典型的方法?我可以想出一些替代方案,比如只将每个算法存储在最终数组中,或者创建一个算法工厂?或者,我不应该为每个算法创建单独的类,而应该只创建一个算法类,该类将AlgorithmType作为加密和解密方法的参数


谢谢。

我不建议将对象存储在枚举中。相反,我建议创建一个键值对映射,并使用Enum作为键,使用算法作为值。有关详细信息,请查看
AbstractMap.SimpleEntry

如果您正在查找模式,请尝试,否则如果实现算法的对象在运行时不更改,请尝试模式。

枚举的意义是什么?
算法
实现不能有一个
toString()
方法吗?将每个
算法
实现的实例放入数组或
列表
有那么难吗?
enum
有什么好处?我不明白,我不知道。一般来说,我认为使用枚举比使用常量列表来保存数据更可取。使用列表基本上与枚举相同。它将在列表中创建每个算法对象,即使它没有在JComboBox中被选中。一定有更好、更有效的方法吗?如果您关心
算法
实例的资源,请创建
算法类型
工厂,根据需要创建
算法
实例
AlgorithmType
可能是一个
enum
(回想一下enum可以实现接口),但它不一定是。我个人更喜欢在将来的版本中保留扩展列表的选项(甚至可能是动态的)。