Strategy Pattern
Conception
- Strategy pattern (also known as the policy pattern) design pattern that enables an algorithm’s behavior to be selected at runtime.
Intent
- Define a family of algorithms, encapsulate each one, and make them interchangeable.
- Strategy lets the algorithm vary independently from the clients that use it.
- Capture the abstraction in an interface, bury implementation details in derived classes.
Example
- Here is the link Duck example
It has structure like this:
The most important part of code should like this:
Duck model = new ModelDuck();
model.performFly();
model.setFlyBehavior(new FlyRocketPowered());
model.performFly();
As you can see, we encapsulate the fly behavior(FlyRocketPowered) algorithm and set a method setFlyBehavior so you guys can change the behavior. The model was like a Context object which is in charge of interaction with Strategy class. So as this way, you can avoid most “if-else” of “switch”, you know what is my mean.
Advantages
- Define a lot of algorithms to make the them can change easily.
- To avoid much duplicate code.
- To make it has good extension function.
Problems
- The caller must understand the difference between each strategy and choose which strategy to use.
- Can not Nested calls, since it suit for flat algorithm structure.
- Add too much objects.
Where
- The class need to select one algorithm for dynamtic
- The only differences between these classes is the behavior.
- Keep the algorithm security and do not want the client know more about the complex data structure.
- Title: Strategy Pattern
- Author: ReZero
- Created at : 2017-05-14 11:22:00
- Updated at : 2025-04-15 23:03:26
- Link: https://rezeros.github.io/2017/05/14/strategypattern/
- License: This work is licensed under CC BY-NC-SA 4.0.
Comments