The strategy pattern is a behavioural pattern. According to Wikipedia is also known as the policy pattern (not sure by whom, but Wikipedia holds a lot of untold truths)
The book definition reads:
Defines a set of encapsulated algorithms that can be swapped to carry out a specific behaviour
To be able to use this pattern properly, take a minute to think about this three things:
- Isolate the behaviors you need and define an interface that applies to all of them.
- Implement the different behaviors. Each behavior IMPLEMENTS the interface.
- The main object HAS-A behavior interface container from which the selected behavior will be called.
Diagram:
Where Would I Use This Pattern?
The Strategy pattern is to be used where you want to choose from algorithms used at runtime
Some examples where you may find this pattern:
- Save to different formats
- Payment methods
- Sorting algorithms
- File compression
References:
No comments:
Post a Comment