简体   繁体   中英

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

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 . If you do as erikb suggests and use a map instead of looping, I would say it's exactly like the Multiton Pattern.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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