java - 切换到 Map/Enum 或其他

标签 java dictionary enums switch-statement

我想知道两件事:

  1. 是否值得从 switch 转换为其他东西
  2. 在我的例子中会是什么样子?对我来说最大的问题是“案例 ID_BOTH:”

我的小菜一碟:

    public void init( int boxID ) {

    initComponentText();

    switch ( boxID ) {

        case ID_IMAGE:
            initComponentImg();
            break;

        case ID_BOOL:
            initComponentBool();
            break;

        case ID_BOTH:
            initComponentBool();
            initComponentImg();
            break;
    }
}

private void initComponentImg() {
    img = new ComponentImg( switchComponent );
}

private void initComponentBool() {
    bool = new ComponentBool( switchComponent );
}

private void initComponentText() {
    text = new ComponentText( switchComponent );
}

感谢您的帮助和提示。

最佳答案

我认为if条件对于降低代码复杂度会更有帮助;

    if(ID_IMAGE==boxID||ID_BOTH==boxID)
        initComponentImg();
    if(ID_BOOL==boxID||ID_BOTH==boxID)
        initComponentBool();

关于java - 切换到 Map/Enum 或其他,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33418278/

相关文章:

java - 相当于java中的ungetc

java - Spring 验证在来自 ServletContext 资源的 XML 文档中有错误

c# - 哪种向 ASP.NET Dictionary 类添加项目的方法效率更高?

design-patterns - 使用字符串与枚举作为工厂方法的参数?

java - 提供 `EntityManagerFactory` 会解决 `Unable to retrieve EntityManagerFactory for unitName xyz`

java - 如何在mysql中获取 "x highest value"

python - 使用字典过滤 pandas 数据框的列值

python - 动态嵌套字典 Python

枚举值定义中的逗号?

c++ - 枚举作为非类型函数模板参数应该彼此不同吗?