2013-07-09 34 views
1

我對每種付款方式都有類,例如, CashChequeCard。我必須傳遞對象作爲基於對象值的參數,我必須實例化一個相關的類。基於對象值實例化特定的類

我該如何做到這一點?建議我一個更好的設計

public interface CollectionInfo { 
    //Code Goes here 
} 

public class Cash implements CollectionInfo { 
    //Code goes here 
} 

public class CollectionFactory { 
    public void newInstance(Enum<CollectionMode> collectionMode) { 
    } 
} 

public interface Receipts { 
    public Receipt createReceipt(String Amount, /*(Here i need to pass parameter of object either cash ,Cheque or card),*/Date date); 
} 
+2

靜態工廠????? – NINCOMPOOP

+2

也許這只是我,但我完全被你所問的問題弄糊塗了。也許你應該包含正在嘗試的代碼和/或僞代碼。 –

+0

*「Registers Vijay」*不包括sigs。在問題中,它們是噪音。另外,不需要在標題中添加主標籤。 –

回答

6

你可以通過枚舉(現金/支票/卡)到工廠?

例如

Payment p = PaymentFactory.newInstance(PaymentMode.Cash); 

和方法中,你會怎麼做:

switch(mode) { 
    case PaymentMode.Cash: 
     return new CashPayment(); 

    // ... 
} 

其中CashPaymentChequePayment等都是Payment子類。

+0

或者如果你想要超級動態,一些命名約定和'Class.forName'。但工廠可能是更好的方式... –

+0

是的。我不想使問題複雜化了太多 –

+0

@BrianAgnew公共接口CollectionInfo { \t \t //代碼放在這裏 } 公共類現金實現CollectionInfo { \t //代碼放在這裏 } 公共類CollectionFactory { \t公共無效的newInstance(枚舉 collectionMode){ \t} } 公共接口收據{ \t \t public Receipt createReceipt(String Amount,/ *(這裏我需要傳遞對象的參數,現金,支票或卡),*/Date date); } – VijayM