Strategy Pattern Under 1 minute - Software Desing Pattern

Rahul KumarRahul Kumar
1 min read

❓ Problem:

You want to choose between different algorithms (sorting, payments, validation, etc.) at runtime.

🧠 Analogy:

Think of an online checkout system: At payment, customers can choose their preferred payment gateway—such as UPI, Credit Card, or PayPal. The checkout process (client code) is agnostic to how each payment method works internally—it simply delegates the payment action to the chosen "strategy."

Python Example: Payment Strategy

Below is a clear Python demonstration of the Strategy Pattern for choosing different payment options at runtime.

from abc import ABC, abstractmethod

class PaymentStrategy(ABC):
    @abstractmethod
    def pay(self, amount):
        pass

class UPIPayment(PaymentStrategy):
    def pay(self, amount):
        print(f"Paying ₹{amount} using UPI.")

class CreditCardPayment(PaymentStrategy):
    def pay(self, amount):
        print(f"Paying ₹{amount} using Credit Card.")

class PayPalPayment(PaymentStrategy):
    def pay(self, amount):
        print(f"Paying ₹{amount} using PayPal.")

class PaymentContext:
    def __init__(self, strategy: PaymentStrategy):
        self._strategy = strategy

    def set_strategy(self, strategy: PaymentStrategy):
        self._strategy = strategy

    def checkout(self, amount):
        self._strategy.pay(amount)

# Choose payment option at runtime
context = PaymentContext(UPIPayment())
context.checkout(500)  # Output: Paying ₹500 using UPI.

context.set_strategy(CreditCardPayment())
context.checkout(750)  # Output: Paying ₹750 using Credit Card.

context.set_strategy(PayPalPayment())
context.checkout(1200)  # Output: Paying ₹1200 using PayPal.

Key Takeaways

  • Flexible algorithms: Swap logic at runtime without changing client code.

  • Easy to extend: Add new behaviors by introducing new strategy classes.

  • Decoupling: Keeps the context class unaware of implementation specifics.

0
Subscribe to my newsletter

Read articles from Rahul Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Rahul Kumar
Rahul Kumar