Author image

Strategy Design Pattern


Difficulty:
1/5


Definition:

Define a family of algorithms, encapsulate each one and make them interchangeable.

It is also known as 'policy' pattern. Instead of implementing a single algorithm directly, code receives run-time instructions as to which in a family of related algorithms to use.

Strategy is a flexible pattern, as it makes combining, adding, changing behaviors of an object easy as pie.

Design

  • create your algorithms as classes, or abstract classes
  • refine your algorithms by inheriting from them
  • create your target object Duck here
  • the target object has pointers to all the possible base algorithms it can support
  • create your object by supplying to it the behaviors you want to provide through its constructor
  • to assign new behaviors simply supply new classes to it

Alternatively, we could define the algorithms as functors or lambdas and have simple objects in the strategic/target object not pointers to those algorithm objects.

Strategy vs State:

In contrast to the State pattern which favors inheritance, Strategy favors composition. Both of them allow you to change object properties @ runtime. With State the object literally changes its class at runtime (requires inheritance). On the other hand, with Strategy the object itself doesn't change, some of its behaviors though can change (requires composition).

When to use it?

Like State, use it when you want an object to rotate among several different behaviors on the fly.

Github

Github repository link.


0 likes