2012-11-06 118 views
-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"); 
     } 
} 

所以,如果一个国家的字符串,例如,是 “印度” 返回卢比。我需要实现的是,如果一个国家的字符串是“全部”,它会以卢比,sgddollars和美元的形式返回所有对象。这种事情的例子是什么?

+0

我不知道你问这里。在“全部”情况下,您是否想要返回*列表*的货币? – home

+0

想要返回数组或列表的“全部”?因为货币对象一次只能是一种类型。 – midhunhk

+0

是的。工厂模式可能吗? – user1788867

回答

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"); 
    } 
+0

嗯,这将需要在低垂呼叫者,例如'((AllCurrency)c)中.rupee' – home

3

为什么不使用Map来查找它?你不必使用模式只是看中。在某些情况下,他们只会让你的代码变得混乱。这样

+1

+1'你不不得不使用花样才能看中'! – home

相关问题