简体   繁体   English

这个枚举模式会被称为什么?

[英]What would this enum pattern be called?

I use this technique frequently but I'm not sure what to call it. 我经常使用这种技术,但我不知道该怎么称呼它。 I call it associative enums. 我称之为关联枚举。 Is that correct? 那是对的吗?

Example: 例:

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;
    }
}

I have a set of classes for doing this but I don't have a name for it other than Encodable 我有一组用于执行此操作的类,但除了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);
      }
}

I would say that looks a fair bit like the Multiton Pattern . 我会说这看起来有点像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. 如果你像erikb建议并使用地图而不是循环那样,我会说它与Multiton模式完全一样。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM