Stopping repetition in Java enums

后端 未结 4 1557
梦谈多话
梦谈多话 2020-12-03 16:26

I have the following enum in a Java class:

public enum Resolution {
    RES_32 (32),
    RES_64 (64);
    private final int asInt;
    private R         


        
4条回答
  •  隐瞒了意图╮
    2020-12-03 17:10

    Why not take the enums out of the class and create a stand-alone enum file that only use the second one (the one with RES_128) for all processing?

    Edit 1
    Your comment:

    Because not all classes should have the same constants. Some need to have only 32 and 64, while others need to have 32, 64 and 128

    There really is only one Resolution "type" and this suggests that there should be but one Resolution enum, but the problem appears to be that not all classes accept all resolutions. One possible solution is to use one enum to represent all resolutions, but have EnumMap for different classes, with some classes marking a resolution false or meaning not valid for that class.

    Edit 2
    Or even just have a HashSet of accepted enums.

    Edit 3
    e.g., using HashSet

    class Foo002 {
       public static Set allowedResolution = new HashSet();
       static {
          allowedResolution.add(Resolution.RES_32);
          allowedResolution.add(Resolution.RES_64);
       }
       private Resolution resolution;
    
       public void setResolution(Resolution resolution) {
          if (!(allowedResolution.contains(resolution))) {
             throw new IllegalArgumentException("Disallowed Resolution: " + resolution);
          }
          this.resolution = resolution;
       }
    }
    
    enum Resolution {
       RES_32 (32),
       RES_64 (64),
       RES_128 (128);
       private final int asInt;
       private Resolution(int asInt) {
           this.asInt = asInt;
       }
    
       public int getIntValue() {
          return asInt;
       }
    };
    

提交回复
热议问题