1

I need to add a new payment type to an existing code base. That means that I'm going to have a few methods looking like this:

if (old payment type)
    process old type of payment
else
    process new type of payment

Now, if this could have been determined beforehand, I would have this method point to an interface implementing a common Pay method and then that interface would be implemented by one of two classes. Unfortunately, I only know which method the customer chooses at runtime, which means I need a way to determine which branch to use. Is there another way except for just having ifs spread through the code?

1 Answers1

5

This is textbook example of Strategy pattern.

...a software design pattern, whereby an algorithm's behaviour can be selected at runtime. Formally speaking, the strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it...

This will allow you to have different implementations of how you pay and you can create the concrete one at runtime based on data saved together with payment.

gnat
  • 20,543
  • 29
  • 115
  • 306
Euphoric
  • 38,149