ReZero's Utopia.

Strategy Pattern

Word count: 241Reading time: 1 min
2017/05/14 Share


  • Strategy pattern (also known as the policy pattern) design pattern that enables an algorithm’s behavior to be selected at runtime.


  • 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.


It has structure like this: Duck Class Graph

The most important part of code should like this:

Duck model = new ModelDuck();
model.setFlyBehavior(new FlyRocketPowered());

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.


  • Define a lot of algorithms to make the them can change easily.
  • To avoid much duplicate code.
  • To make it has good extension function.


  • 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.


  • 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.
  1. 1. Conception
  2. 2. Intent
  3. 3. Example
  4. 4. Advantages
  5. 5. Problems
  6. 6. Where