-4

我的 Java 应用程序中有一个工厂。看起来像:

// Common Interface
 interface Currency {
   String getSymbol();
  }

// Concrete Rupee Class code
class Rupee implements Currency {
       @Override
       public String getSymbol() {
              return "Rs";
       }
}

// Concrete SGD class Code
class SGDDollar implements Currency {
       @Override
       public String getSymbol() {
              return "SGD";
       }
}


// Concrete US Dollar code
class USDollar implements Currency {
       @Override
       public String getSymbol() {
              return "USD";
       }
}

我有一个FactoryClass:

class CurrencyFactory {

       public static Currency createCurrency (String country) {
       if (country. equalsIgnoreCase ("India")){
              return new Rupee();
       }else if(country. equalsIgnoreCase ("Singapore")){
              return new SGDDollar();
       }else if(country. equalsIgnoreCase ("US")){
              return new USDollar();
        }
       throw new IllegalArgumentException("No such currency");
       }
}

因此,例如,如果一个国家/地区字符串是“印度”,它会返回卢比。我需要实现,如果国家字符串是“全部”,它会将所有对象返回为卢比、新元和美元。有这样的例子吗?

4

2 回答 2

3

你为什么不使用 aMap来查找它?您不必为了花哨而使用模式。在某些情况下,它们只会使您的代码变得混乱。

于 2012-11-06T17:12:54.283 回答
0

尝试这样的事情

创建一个类作为 AllCurrency

 public class AllCurrency implements Currency{

private Rupee rupee;
private SGDDollar sgdDollar;
private USDollar useDoler;

public AllCurrency (Rupee rupee,SGDDollar sgDoler,USDollar usDoller){
    this.rupee = rupee;
    this.sgdDollar = sgDoler;
    this.usDoller = usDoller
}

@Override
   public String getSymbol() {
          return "all";
   }

// add getters and setters

}

还有你的工厂

public static Currency createCurrency (String country) {
   if (country. equalsIgnoreCase ("India")){
          return new Rupee();
   }else if(country. equalsIgnoreCase ("Singapore")){
          return new SGDDollar();
   }else if(country. equalsIgnoreCase ("US")){
          return new USDollar();
    }else if(country. equalsIgnoreCase ("all")){
          return new AllCurency(new Rupee(),new SGDDollar(),new USDollar());
    }
   throw new IllegalArgumentException("No such currency");
   }
于 2012-11-06T17:23:45.690 回答