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

It has structure like this:

Duck Class Graph


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

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐