Sunday, October 13, 2013

Instantiate particular class based on object value

I have classes for each payment mode for e.g. Cash, Cheque, Card. I have to pass object as a parameter based on object value I have to instantiate a relevant class.

How can I achieve this? Suggest me a better design

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);}

You could pass an enumeration (Cash/Cheque/Card) into a factory ?

e.g.

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

and within that method you would do:

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

where CashPayment, ChequePayment etc. are subclasses of Payment.

No comments:

Post a Comment