Strategy Pattern

ReZero lol

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