切换到 Map/Enum 或其他

Switch to Map/Enum or something else

我想知道两件事:

  1. 是否值得从 switch 转换为某种东西
  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 );
}

感谢您的帮助和提示。

我觉得if条件会更有利于降低代码的复杂度;

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

假设您让 ID_BOTH 成为 ID_BOOLID_IMAGE 的按位或,并且您的个人 "types" 没有重叠的二进制值(例如2),可以按位与boxId来检查个性。使用这种方法,您可以将所有类型按位或运算在一起。

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
}

您可以改用 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