Skip to content

Strategy Pattern - Separate Behavior from Implementations

Updated: at 12:00 AM

1. The Problem

Problem: Multiple Ways to Do the Same Thing

Software frequently needs to support several interchangeable algorithms. Example: compressing files using ZIP, RAR, or GZIP.

Hard-coding these variations leads to rigid, branching-heavy code:

if type == "zip": ...
elif type == "rar": ...
elif type == "gzip": ...

This creates a maintenance burden, violates the Open/Closed Principle, and becomes unscalable as options grow. We need interchangeable algorithms without modifying the code that uses them.

2. The Strategy Pattern: Decouple What You Do from How You Do It

The Strategy Pattern solves this by separating behavior from implementation.

Core idea:

A system using Strategy has two parts:

The context only sees the abstract algorithm, not the concrete type. You get:

Use Strategy when:

3. Implementation: Strategy + Context in Python

Strategy interface:

from abc import ABC, abstractmethod

class CompressionStrategy(ABC):
    @abstractmethod
    def compress(self, data) -> str:
        pass

Concrete strategies:

class ZipCompressionStrategy(CompressionStrategy):
    def compress(self, data) -> str:
        return f"Data compressed using ZIP: {data}"

class RarCompressionStrategy(CompressionStrategy):
    def compress(self, data) -> str:
        return f"Data compressed using RAR: {data}"

class GZipCompressionStrategy(CompressionStrategy):
    def compress(self, data) -> str:
        return f"Data compressed using GZIP: {data}"

Context that delegates to a strategy:

class Compressor:
    def __init__(self, strategy: CompressionStrategy):
        self._strategy = strategy

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

    def compress_data(self, data) -> str:
        return self._strategy.compress(data)

Runtime swapping:

context = Compressor(ZipCompressionStrategy())
context.set_strategy(RarCompressionStrategy())

4. When to Use Strategy (and When Not To)

You likely need Strategy when you notice:

Common pitfalls: