strategy-pattern-python
Installation
SKILL.md
Strategy Pattern (Python Backend)
Why: Strategy lets you define a family of algorithms, put each in a separate class, and make them interchangeable so the context stays stable while behavior is swapped at runtime (Refactoring.Guru).
Hard constraints: Context must depend only on a strategy protocol/ABC, not concrete implementations. Use composition (context holds a strategy reference); avoid inheritance for variant behavior. Keep each strategy in its own class/module when it has real logic.
When to use
- Different variants of the same algorithm (e.g. payment methods, route builders, serializers) and you want to switch at runtime.
- A class is bloated with conditionals (e.g.
if method == "card": ... elif method == "paypal": ...); extract each branch into a strategy. - You need to isolate algorithm details from the rest of the backend logic (Open/Closed: add strategies without changing context).