6

我经常使用这种技术,但我不知道该怎么称呼它。我称之为关联枚举。那是对的吗?

例子:

public enum Genders {

    Male("M"), Female("F"), Transgender("T"), Other("O"), Unknown("U");

    private String code;

    Genders(String code) {
        this.code = code;
    }

    public String getCode() {
        return code;
    }

    public static Genders get(String code) {
        for (Genders gender : values()) {
            if (gender.getCode().equalsIgnoreCase(code)) {
                return gender;
            }
        }
        return null;
    }
}
4

3 回答 3

3

我有一组用于执行此操作的类,但除此之外我没有其他名称Encodable

interface Encodable<T>{
    T getCode();
}

public class EnumUtils{

      public static <U, T extends Enum<T> & Encodable<U>> T getValueOf(
            @Nonnull Class<T> enumClass,
            @Nullable U code){

            for (T e : enumClass.getEnumConstants()){
               if (Objects.equal(e.getCode(), code))
                  return e;
            }

            throw new IllegalArgumentException("No enum found for " + code);
      }
}
于 2012-06-11T21:27:40.390 回答
2

I would say that looks a fair bit like the Multiton Pattern. If you do as erikb suggests and use a map instead of looping, I would say it's exactly like the Multiton Pattern.

于 2012-06-11T21:38:30.843 回答
1

我会说这是一个非常非常简单的解析器。

于 2012-06-11T21:29:30.137 回答