java使用枚举类型解决if-else大量堆积

调用代码

import com.example.javaone.kk.MyEnum;

public class Gst {

    public static void main(String[] args) {
        MyEnum e=MyEnum.getById(1);
        System.out.println(e.getGetSize());
    }
}

被调用代码

package com.example.javaone.kk;
public enum MyEnum {
  ENUM1(1,2),
  ENUM2(2,3),
  ENUM3(3,4);
  private int id;
  public int getGetSize() {
    return getSize;
  }
  private  int getSize;
  MyEnum(int id,int getSize) {
    this.id = id;
    this.getSize = getSize;
  }
  public int getId() {
    return id;
  }
  public static MyEnum getById(int id) {
    for (MyEnum enumValue : MyEnum.values()) {
      if (enumValue.getId() == id) {
        return enumValue;
      }
    }
    throw new IllegalArgumentException("Invalid ID: " + id);
  }
}

该代码可以解决多个if-else 而且可以解决多个模块使用多个if-else

你可能感兴趣的:(java,开发语言)