The Strategy pattern packages a family of algorithms behind a common contract. It is useful when the application selects among behaviors that are expected to evolve independently.
Recognize the right problem
A few stable branches may be clearer as a conditional. Strategy becomes valuable when each branch has substantial logic, changes at a different pace, or needs independent testing. Examples include pricing rules, export formats, shipping calculations, or authentication providers.
Define a focused contract
The strategy interface should express the operation callers need. Keep provider-specific options inside the implementation or a typed configuration object. Avoid a universal interface with many optional parameters that every strategy ignores differently.
Select strategies explicitly
A registry or factory can map a known key to an implementation. Validate the key and provide a clear unsupported-case response. Do not let untrusted input choose arbitrary class names or instantiate arbitrary services.
Test the contract
Run shared contract tests against every implementation. Then test each strategy's unique edge cases. This helps ensure implementations remain substitutable.
Checklist
- Confirm behavioral variation is likely to grow.
- Keep the strategy contract narrow.
- Use an allowlisted registry for selection.
- Avoid optional-parameter-heavy interfaces.
- Test common guarantees across implementations.