我的Java appplication中有一个工厂。它看起来像:
// 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");
}
}
因此,如果国家字符串是“印度”,则返回卢比。我需要实现,如果一个国家字符串是“全部”它返回所有对象作为卢比,sgddollars和美元。这样的事情有什么例子吗?
答案 0 :(得分:3)
为什么不使用Map
进行查找?您不必使用模式只是为了花哨。在某些情况下,他们只会使你的代码变得混乱。
答案 1 :(得分: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");
}