"如果"声明与OO设计

问题描述:

我有枚举说错误代码

public enum ErrorCodes { 
       INVALID_LOGIN(100),
       INVALID_PASSWORD(101),
       SESSION_EXPIRED(102) ...;

       private int errorCode;

       private ErrorCodes(int error){
              this.errorCode = error;
       }    //setter and getter and other codes
}

现在我检查我的异常错误代码与此错误代码。如果这样做,我不想写。我如何解决这个问题(写10+如果块)

now I check my exception error codes with this error codes. I don't want to write if this do this, if this do this. How I can solve this problem (writing 10+ if blocks)

有没有任何设计模式,这种情况?

Is there any design patter to that situation ?

谢谢

如Spoike所指出的,使用多态选择正确的错误处理方法是一个选项。通过定义一个类层次结构,这种方法基本上可以通过定义一个类层次结构来推迟10个以上的JVM虚拟方法查找。

As pointed out by Spoike, using polymorphism to pick the right error handling method is an option. This approach basically defers the 10+ if blocks to the JVM's virtual method lookup, by defining a class hierarchy.

但是,在进行完整的类层次结构之前,还要考虑使用枚举方法。如果您计划在每种情况下做的事情是非常相似的,那么此选项将很有效。

But before going for a full-blown class hierarchy, also consider using enum methods. This option works well if what you plan to do in each case is fairly similar.

例如,如果要为每个 ErrorCode ,你可以这样做:

For example, if you want to return a different error message for each ErrorCode, you can simply do this:

// Note singular name for enum
public enum ErrorCode { 
   INVALID_LOGIN(100, "Your login is invalid"),
   INVALID_PASSWORD(101, "Your password is invalid"),
   SESSION_EXPIRED(102, "Your session has expired");

   private final int code;
   private final String 

   private ErrorCode(int code, String message){
          this.code = code;
          this.message = message;
   }

   public String getMessage() {
       return message;
   }
}

然后,您的错误处理代码变为:

Then your error handling code becomes just:

ErrorCode errorCode = getErrorCode();
prompt(errorCode.getMessage());

这种方法的一个缺点是如果要添加其他案例,则需要修改枚举本身,而使用类层次结构,您可以添加新的案例,而无需修改现有代码。

One drawback of this approach is that if you want to add additional cases, you'll need to modify the enum itself, whereas with a class hierarchy you can add new cases without modifying existing code.