Strategy Pattern

ReZero lol


  • 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.
  • Post title:Strategy Pattern
  • Post author:ReZero
  • Create time:2017-05-14 11:22:00
  • Post link:
  • Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.