Course contentsShow
← Computer Science
Lesson 2288 of 2,87251. Design PatternsFree lesson

Strategy Pattern Implementation

Implementing strategy pattern with concrete strategies, context classes, and dynamic algorithm selection.

Strategy Pattern Implementation

You'll learn how to build a working Strategy Pattern by creating concrete strategy classes, a context class, and switching algorithms at runtime.

Core Idea

The Strategy Pattern implementation consists of three parts: concrete strategies (classes that implement different algorithms), a context class (holds and uses a strategy), and dynamic selection (swapping strategies on the fly). Think of it like a GPS app that can switch between "fastest route," "shortest distance," or "avoid tolls" algorithms without changing the navigation interface.

Implementation Structure

Define Strategy Classes

Each concrete strategy implements the same interface but with different logic:

class FastestRoute:
    def calculate(self, start, end):
        return "Using highways for speed"

class ShortestDistance:
    def calculate(self, start, end):
        return "Using direct path"

Build the Context

The context holds a reference to a strategy and delegates work to it:

class Navigator:
    def __init__(self, strategy):
        self.strategy = strategy
    
    def set_strategy(self, strategy):
        self.strategy = strategy
    
    def get_route(self, start, end):
        return self.strategy.calculate(start, end)

Dynamic Algorithm Selection

Switch strategies at runtime based on conditions:

nav = Navigator(FastestRoute())
print(nav.get_route("A", "B"))  # Uses fastest

nav.set_strategy(ShortestDistance())
print(nav.get_route("A", "B"))  # Now uses shortest

The context doesn't know implementation details—it just calls the same method on whatever strategy it holds. This makes adding new strategies easy: create a new class with the same method signature.

Key Takeaway: Strategy Pattern implementation requires concrete strategy classes sharing a common interface, a context class that delegates to the current strategy, and the ability to swap strategies dynamically without changing the context's code.