使用枚举类型时如何避免if语句等于?

时间:2017-04-04 12:55:13

标签: java

使用枚举类型时,是否存在某种避免许多if语句的方法?也许我应该使用一些设计模式而不是使用if语句。

我的代码中有很多个例子,如下所示://伪代码

public void methodOne() {    
    if(User.Type.SomeType == user.Type && User.Type.SecondType == user.Type)
        doSomething();
}

public void methodTwo() {
    if(!User.Type.OtherType == user.Type && !User.Type.SecondType == user.Type)
        throw new BadTypeException();
    doSomething();
}

3 个答案:

答案 0 :(得分:5)

使用EnumSet

private static final Set<User.Type> SET = EnumSet.of(User.Type.SomeType, User.Type.SecondType);

if (SET.contains(user.type)) {
}

答案 1 :(得分:1)

就个人而言,我特别喜欢在这种情况下使用vararg函数

private static boolean matchesAnyState(User.Type type, User.Type... types) {
    for (User.Type listType: types) {
        if (type.equals(listType)) {
            return true;
        }
    }
    return false;
} 

答案 2 :(得分:0)

当然,您可以创建一个实用程序类并将这些检查移动到静态方法,但这不是OOP方式,也不会修复您的设计。

相反,我会建议你考虑将用户子类化。 因此,您不必拥有User.Type,而是拥有interface Userabstract class User和子类型:

class AdminUser implements User

class GuestUser implements User

等等。 方法doSomething应移至您的User接口并由子类实现。 而且您只需要求您的用户doSomething