Behavioral PatternsStrategy PatternMedium⏱️ ~3 min

Strategy Pattern - Structure and Participants

Core Participants

The Strategy Pattern involves three key participants with distinct responsibilities:

«interface»
Strategy
+ execute(data): Result
ConcreteStrategyA
+ execute(data): Result
ConcreteStrategyB
+ execute(data): Result
Context
- strategy: Strategy
+ setStrategy(s: Strategy)
+ doOperation(data): Result

Participant Responsibilities

First, Strategy Interface: Declares the common interface for all supported algorithms. This is typically a single method that concrete strategies must implement. The method signature must be generic enough to accommodate all algorithm variations.

Second, Concrete Strategy Classes: Implement the Strategy interface with specific algorithm logic. Each concrete strategy is a self-contained unit that can be tested independently. These classes should be stateless when possible, receiving all necessary data through method parameters.

Third, Context Class: Maintains a reference to a Strategy object and delegates algorithm execution to it. The context is decoupled from specific implementations, knowing only the Strategy interface. It may pass itself as an argument to the strategy if the strategy needs access to context data.

Relationships

The Context has an aggregation relationship (◇) with Strategy, meaning the context holds a reference but does not own the strategy's lifecycle. Concrete strategies inherit (▲) from the Strategy interface using interface realization.

Interview Tip: Clarify that Context does not create strategies (that is Factory's job). Strategies are typically injected via constructor or setter, following Dependency Injection principles.

Method Flow

When a client needs an operation performed: First, client creates or retrieves the appropriate concrete strategy. Second, client sets the strategy on the context using setStrategy(). Third, client calls the context's operation method. Fourth, context delegates to its current strategy's execute() method. Fifth, strategy returns the result, which the context may transform or pass through.

💡 Key Takeaways
Strategy interface defines the contract all algorithms must follow
Concrete strategies implement specific algorithm variations independently
Context holds a reference to Strategy and delegates execution to it
Aggregation relationship allows runtime strategy swapping
Client is responsible for selecting and injecting the appropriate strategy
📌 Examples
1Strategy as interface with execute() method
2Context with setStrategy() for runtime switching
3Multiple concrete strategies sharing a common interface signature
← Back to Strategy Pattern Overview
Strategy Pattern - Structure and Participants | Strategy Pattern - System Overflow