【问题标题】:Switch to Map/Enum or something else切换到 Map/Enum 或其他
【发布时间】:2015-10-29 15:24:41
【问题描述】:

我想知道两件事:

  1. 从 switch 转换为 something 是否值得
  2. 在我的情况下会是什么样子?对我来说最大的问题是“case 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 );
}

感谢您的帮助和提示。

【问题讨论】:

  • 在我的情况下会是什么样子?在你的情况下什么会是什么样子?

标签: java dictionary enums switch-statement


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    假设您让 ID_BOTH 成为 ID_BOOLID_IMAGE 的按位或,并且您的各个“类型”没有重叠的二进制值(例如 2 的幂),您可以按位与 @987654324 @ 检查个性。使用这种方法,您可以将所有类型保持按位或运算。

    int ID_NONE = 0
    int ID_BOOL = 1;
    int ID_IMAGE = 2;
    int ID_TEXT = 4;
    
    int ID_BOOL_IMG = ID_BOOL | ID_IMAGE; // 3
    int ID_BOOL_TEXT = ID_BOOL | ID_TEXT; // 5
    int ID_BOOL_ALL = ID_BOOL | ID_IMAGE | ID_TEXT; // 7
    
    if ((boxId & ID_BOOL) == ID_BOOL) {
        initComponentBool(); // runs for boxId = 1, 3, 7
    }
    if ((boxId & ID_IMAGE) == ID_IMAGE) {
        initComponentImg(); // runs for boxId = 2, 3, 7
    }
    if ((boxId & ID_TEXT) == ID_TEXT) {
       initComponentText(); // runs for boxId = 4, 5, 7
    }
    

    【讨论】:

    • 如果 boxID = ID_BOTH ??
    • 这不处理 ID_BOTH。您是否正在考虑将 boxID 更改为按位或值?
    • 猜你是对的 :) 我在思考逻辑而不是编程。
    • 答案按位更新。感谢您的想法,@AndyThomas
    • @Shivam - 添加else if 将导致仅输入第一个匹配条件。
    【解决方案3】:

    您可以改用bitwise AND 运算符

    public void init( int boxID ) {
      initComponentText();
    
      if ((boxID & ID_IMAGE) == ID_IMAGE) initComponentImg();
      if ((boxID & ID_BOOL) == ID_BOOL) initComponentBool();
    }
    

    假设

    int ID_IMAGE = 1;
    int ID_BOOL = 2;
    int ID_BOTH = 3;
    

    DEMO

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多