The strategy pattern
This design pattern is also referred to as the policy pattern saying policy to be selected at runtime.
Note
The strategy design pattern is used to determine an algorithm at runtime to solve a problem.
We will continue with the example of the Music Library portal, as discussed in the visitor pattern and observer pattern. As part of the implementation, developers want to add support for payment in the shopping cart. However, the customer's selected payment type can be known only during a checkout. Customers can use either a credit card, debit card, or PayPal. Let's see how the strategy pattern can come in handy in this situation.
For this example, let's consider the following structure for a song (a Music Library custom object), which can be added to the shopping cart:
![](https://static.packt-cdn.com/products/9781782173656/graphics/image_04_020.jpg)
The following interface needs to be implemented by all the payment methods so that it can be selected at runtime:
/* * This interface needs to be implemented by all classes * of Payment types which...