Strategy Pattern - Structure and Participants
Core Participants
The Strategy Pattern involves three key participants with distinct responsibilities:
+ 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.
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.