糟糕的if-else或switch结构的Java替代品

pob*_*obu 7 java oop design-patterns

寻找现代的方法来实现字符串翻译,以取代看起来很糟糕的if-else或switch结构:

if ("UK".equals(country)) 
     name = "United Kingdom";
  if ("GE".equals(country))
     name = "Germany";
  if ("FR".equals(country))
     name = "France";
  if ("IT".equals(country))
     name = "Italy";
  [...]
Run Code Online (Sandbox Code Playgroud)

要么

switch (country) {
      case "UK": name = "United Kingdom"; break;
      case "GE": name = "Germany" break;
      case "FR": name = "France"; break;
      case "IT": name = "Italy" break;
  [...]
Run Code Online (Sandbox Code Playgroud)

dan*_*niu 15

你可能想要一个enum.

public enum Country {
    UK("United Kingdom"),
    GE("Germany"), // sure this isn't DE?
    FR("France");
    // and so on
    private String countryName;
    private Country(String n) { countryName = n; }

    public String getCountryName() { return countryName; }
}
Run Code Online (Sandbox Code Playgroud)

现在你可以

Country c = Country.valueOf(countryString); // throws exception when unknown
name = c.getCountryName();
Run Code Online (Sandbox Code Playgroud)


m f*_*bdi 0

您可以简单地使用 java.util.Map。
创建静态国家变量。

private static final String UK = "UK";
private static final String GE = "GE";
private static final String FR = "FR";
private static final String IT = "IT";

private static final Map<String, String> COUNTRIES;
static {
    final Map<String, String> countries = new HashMap<>();
    countries.put(UK, "United Kingdom");
    countries.put(GE, "Germany");
    countries.put(FR, "France");
    countries.put(IT, "Italy");
    COUNTRIES = Collections.unmodifiableMap(countries);
}
Run Code Online (Sandbox Code Playgroud)

然后可以使用 java.util.Map 中的“get”属性来获取国家/地区名称

System.out.println(COUNTRIES.get(UK));
System.out.println(COUNTRIES.get(GE));
System.out.println(COUNTRIES.get(FR));
System.out.println(COUNTRIES.get(IT));
Run Code Online (Sandbox Code Playgroud)