首页 > 解决方案 > Java 替代看起来很糟糕的 if-else 或 switch 结构

问题描述

寻找实现字符串翻译的现代方法来替换难看的 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";
  [...]

或者

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

标签: javaoopdesign-patterns

解决方案


你可能想要一个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; }
}

现在你可以

Country c = Country.valueOf(countryString); // throws exception when unknown
name = c.getCountryName();

推荐阅读