尝试用Java中的枚举替换switch语句

时间:2019-01-30 15:34:19

标签: java enums switch-statement refactoring

我有一个下面的类,该类使用switch语句,我想用一个枚举代替它。

public class FillTable {

    private static final int NAME_INDEX = 0;
    private static final int DESCRIPTION_INDEX = 1;
    private static final int CONTRIBUTION_INDEX = 2;

    public Object getValueAt(int row, int col) {
        EmployeeData employeeData = (EmployeeData)items.get(row);

        switch (col) {
            case NAME_INDEX: {
                return employeeData.getName();
            }
            case DESCRIPTION_INDEX: {
                return employeeData.getDescription();
            }
            case ADDRESS_INDEX: {
                return employeeData.getAddress();
            }
            default: {
                return "";
            }
        }
    }

}

下面是枚举,我已经想出。

public enum EmployeeTableColumn {

    NAME_INDEX {
        @Override
        public void getData() {
            employeeData.getName();
        }
    }, DESCRIPTION_INDEX {
        @Override
        public void getData() {
            return employeeData.getDescription();
        }
    }, CONTRIBUTION_INDEX {
        @Override
        public void getData() {
            return employeeData.getAddress();
        }
    };

    public abstract void getData();

}

我的问题是我不知道如何替换getValueAt()方法中的代码以使用枚举代替switch语句。是否有人可以告诉我我该怎么办呢?

1 个答案:

答案 0 :(得分:2)

如果您希望EmployeeTableColumn枚举控制如何从EmployeeData对象提取信息,则需要在EmployeeTableColumn中使用将EmployeeData作为参数的方法并返回提取的信息。

public enum EmployeeTableColumn {
    NAME {
        @Override
        public Object getData(EmployeeData data) {
            return data.getName();
        }
    },
    DESCRIPTION {
        @Override
        public Object getData(EmployeeData data) {
            return data.getDescription();
        }
    },
    CONTRIBUTION {
        @Override
        public Object getData(EmployeeData data) {
            return data.getAddress();
        }
    };

    public abstract Object getData(EmployeeData data);
}

然后,您可以编写使用EmployeeTableColumn提取正确数据的方法。

public Object getValueAt(int row, int col) {
    EmployeeData employeeData = (EmployeeData)items.get(row);

    // however you are going to pick the right column object
    EmployeeTableColumn employeeColumn = EmployeeTableColumn.values()[col];

    return employeeColumn.getData(employeeData);
}