What is the Strategy Pattern
The Strategy Pattern is a behavioral design pattern that defines a family of algorithms, encapsulates each one, and makes them interchangeable.
The algorithm can vary independently from clients that use it.
Pattern Structure
The Strategy Pattern consists of three main parts:
- A **Context** that uses a Strategy object.
- A **Strategy Interface** defining a method signature.
- One or more **Concrete Strategies** implementing different behaviors.
Strategy Pattern UML Diagram
Implementation Example in Python
The following example implements a payment system where the payment method can be changed at runtime using the Strategy Pattern.
from abc import ABC, abstractmethod
# Strategy Interface
class PaymentStrategy(ABC):
@abstractmethod
def pay(self, amount):
pass
# Concrete Strategies
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 BitcoinPayment(PaymentStrategy):
def pay(self, amount):
print(f"Paying {amount} using Bitcoin.")
# Context
class PaymentContext:
def __init__(self, strategy: PaymentStrategy):
self.strategy = strategy
def set_strategy(self, strategy: PaymentStrategy):
self.strategy = strategy
def pay(self, amount):
self.strategy.pay(amount)
# Example usage
payment = PaymentContext(CreditCardPayment())
payment.pay(100)
payment.set_strategy(BitcoinPayment())
payment.pay(250)
When to Use
Use the Strategy Pattern when:
- There are multiple related classes differing only in their behavior.
- You need different variants of an algorithm.
- An algorithm uses data that clients should not know about.
- You want to isolate code from conditional statements on behaviors.
Summary
The Strategy Pattern organizes related algorithms into separate classes and allows their interchangeability at runtime without modifying the Context that uses them.