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 algorithms to use.

Strategy vs State:

In contrast to the State pattern which favors inheritance, Stategy favors composition, while both allowing you to change object properties @ runtime. with State the object literally changes its class at runtime (requires inheritance). With Strategy the object itself doesn't change, some of its behaviors though can change (requires composition).

Design

  • create your algorithms as classes, or abstract classes
  • refine your algorithms by inheriting from them
  • create your target object
  • 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 ctor
  • 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.

When to use it?

  • Strategy is a flexible pattern, as it makes combining, adding, changing behaviors of an object easy as pie.
  • Use it when you want an object to have one of several behaviors dynamically.

Github

Github repository link.


0 likes