I frequently seems to come up to a situation where I have an abstract type which needs to be processed differently depending on which concrete implementation it has.
As an example, an abstract class Payment
could be subclassed as class CreditCard
or class StoredCredit
. To actually process the payment, we want to use an implementation of
interface IPaymentTaker {
PaymentProcessingResult Process(Payment payment); }
i.e. either
class CreditCardPaymentTaker : IPaymentTaker { ... }
or
class StoredCreditPaymentTaker : IPaymentTaker { ... }
In the past I have injected an IDictionary into the parent component and then done
_paymentTakers[payment.GetType()].Process(payment);
The downside of this is that the IPaymentTaker
implementations are not strongly typed enough, so the first bit of the Process method has to be:
Process(Payment payment)
{
var creditCardPayment = payment as CreditCardPayment;
if (creditCardPayment == null)
throw new Exception("Payment must be of type CreditCard");
}
I'm sure there must be a name for the pattern I'm trying to implement but I don't know what it is!
Ideally I would
(a) be able to instantiate the PaymentProcessor based just on the type of the Payment, without creating the dictionary;
(b) be able to have strongly typed PaymentProcessors that only accept the subclass they can use.
Does anyone have a neat way of solving this problem?