Strategy Desing Pattern
Strategy Desing Pattern
Design Patterns
Overview
Intent
Also Known As
Motivating Example
Applicability
Implementation Example
Consequences
Known Uses
Related Patterns
Motivating Example
An order shipping calculator
The calculator must determine shipping costs
For FedEx
For UPS
For the US Postal Service (USPS)
Intent
Encapsulate a family of related algorithms
Let the algorithm vary and evolve separate from the class using
it
Allow a class to maintain a single purpose
Separate the calculation from the delivery of its results
Applicability
Switch statements are a red flag
Adding a new calculation will cause a class file to be modified
Implementation Example
Create classes for each calculation (Strategies)
Use a common interface for each Strategy
Consequence
Strategies may not use members
of the containing class
Tests may now be written for individual concrete strategies
Strategies may be mocked when testing the Context class
Adding a new Strategy does not modify the Context class
Known Uses
Delegates in C# 3.5 and greater
Service classes passed to constructors for
Variations
Property Injection
Related Patterns
References