Strategy Pattern: Definition, Example, and When to Use
Strategy Pattern is a design pattern that lets you choose an algorithm’s behavior at runtime by defining a family of algorithms and making them interchangeable. It helps separate the algorithm from the object that uses it, allowing flexible and reusable code without changing the client.How It Works
Imagine you have a remote control that can switch between different TV channels. The remote itself doesn’t know how each channel works; it just switches the channel based on your choice. Similarly, the Strategy Pattern lets an object pick from different algorithms or behaviors at runtime without changing its own code.
In this pattern, you define a set of strategies (algorithms) that share a common interface. The main object holds a reference to one of these strategies and delegates the work to it. You can change the strategy anytime, making the system flexible and easy to extend.
Example
This example shows a simple text formatter that can format text in different ways using the Strategy Pattern.
from abc import ABC, abstractmethod class TextFormatter(ABC): @abstractmethod def format(self, text: str) -> str: pass class UpperCaseFormatter(TextFormatter): def format(self, text: str) -> str: return text.upper() class LowerCaseFormatter(TextFormatter): def format(self, text: str) -> str: return text.lower() class TextEditor: def __init__(self, formatter: TextFormatter): self.formatter = formatter def set_formatter(self, formatter: TextFormatter): self.formatter = formatter def publish_text(self, text: str) -> str: return self.formatter.format(text) # Usage editor = TextEditor(UpperCaseFormatter()) print(editor.publish_text("Hello Strategy Pattern")) # HELLO STRATEGY PATTERN editor.set_formatter(LowerCaseFormatter()) print(editor.publish_text("Hello Strategy Pattern")) # hello strategy pattern
When to Use
Use the Strategy Pattern when you have multiple ways to perform a task and want to switch between them easily without changing the client code. It is helpful when you want to avoid many conditional statements that select behavior.
Real-world examples include payment methods in an online store (credit card, PayPal, etc.), sorting algorithms that can be swapped based on data size, or different ways to compress files. This pattern improves code maintainability and makes adding new behaviors simple.
Key Points
- Defines a family of interchangeable algorithms.
- Encapsulates each algorithm separately.
- Lets the client choose the algorithm at runtime.
- Reduces conditional statements in code.
- Improves flexibility and maintainability.