Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 

Also known as Policy.

Intend

As stated in GoF, p315 :

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

You should use the Strategy pattern in the following cases :

  • You need to use several algorithms with different variations.
  • You want to be able to change the algorithm at run-time.
  • You want to eliminate several conditional statements for algorithms decisions.
  • You have a lot of similar classes that only differ in the way they execute some behaviour.

How it's done

UML

Participants

  • Context
    • Is configured with a ConcreteStrategy object.
    • Maintains a reference to that object.
  • Strategy
    • Declares an interface common to all algorithms.
  • ConcreteStrategy
    • Implements the algorithm using the Strategy interface.

How to implement

  1. Identify an algorithm that is prone to frequent change.
  2. Declare the Strategy interface that aggregates common parts (high-level behaviour) of every algorithms ( ConcreteStrategy ).
  3. Implement every algorithm in its own ConcreteStrategy class.
  4. Add a field to store a reference to a ConcreteStrategy object In the Context class. Provide the client with a setter to replace that field.
  5. That it it ! The client should now associate its Context with the ConcreteStrategy it needs and get the job done.

Note : UML class diagram taken from here

Pros & cons

Pros

  • Alternative to subclassing : Subclassing can achieve the same goal (i.e. support a variety of behaviors) but hard-wires them into Context, which make that Context harder to understand and maintain.
  • Improves readability by eliminating conditional code for Concretestrategies (algorithms).
  • Single responsability principle : One class by strategy.
  • Open/closed principle : It is easy to add new ConcreteStrategies without breaking any code or any need to change existing code.

Cons

  • The client should have some knowledge on the differences between the ConcreteStrategies to be able to select the one it needs.

Notes

Here are some usefull ressources :