Imagine you are developing an e-commerce app. When a user checks out, they can choose from different payment methods:
Each method has a different algorithm/logic for processing payments.
Problem:
If you try to handle all payment methods in a single PaymentProcessor
class using
if-else
or switch
, your code will:
๐ก Strategy Pattern Solution:
We define a common interface for all payment methods. Then, we plug in the appropriate payment strategy at runtime.
UML Diagram:
Output:
Paid Rs. 1500.0 using Credit Card. Paid Rs. 5000.0 using PayPal. Paid Rs. 12000.0 using Cryptocurrency.