The Strategy Pattern is a behavioral design pattern from the book Design Patterns: Elements of Reusable Object-Oriented Software”. It defines a family of algorithms and encapsulates them in objects.
The Strategy Pattern is heavily used in the Standard Template Library.
The Strategy Pattern
- Defines a family of algorithms and encapsulates them in objects
Also known as
- Different variations of an algorithm are needed
- The client does not need to know the algorithm
- The algorithm should be exchangeable at the run time of a program
- Defines the interface for the family of algorithms
- Implements an algorithm
- Manages a reference to a
- Has a
Context has a
ConcreteStrategy that is encapsulated in an object. The
ConcreteStrategy implements the interface of
Strategy. Typically, the
ConcreteStrategy can be adjusted during run time.
The following example
strategy.cpp uses three concrete strategies and follows the naming conventions in the previous image.
Context has a strategy (line 1) that can be set (line 2) and can be executed (line 3). Each strategy has to support the member function
execute (line 4). The
main program uses three concrete strategies, sets them, and executes them. Here is the output of the program.
Usage in C++
The Strategy Pattern is heavily used in the Standard Template Library. In the case of templates, we call it Policy.
A policy is a generic function or class whose behavior can be configured. Typically, there are default values for the policy parameters.
std::unordered_map exemplifies policies in C++.
This means each container has a default allocator for its elements depending on T (line 1) or on
std::pair<const Key, T> (line 2). Additionally,
std::unorderd_map has a default hash function (line 3) and a default equal function (4). The hash function calculates the hash value based on the key, and the equal function deals with collisions in the buckets. My previous post “Hash Functions” gives you more information about
Consequentially, you can use a user-defined data type such as
MyInt as a key in a
I implemented the hash function (line 1), and the equal function (line 2) as a function object and overloaded, for convenience reasons, the output operator (line 3). Line 4 creates out of all components a new type MyIntMap, that uses
MyInt as a
key. The following screenshot shows the output of the instance
- The Template Method and Strategy Pattern use cases are pretty similar. Both patterns enable it to provide variations of an algorithm. The Template Method is based on a class level by subclassing, and the Strategy Pattern on an object level by composition. The Strategy Pattern gets is various strategies as objects and can, therefore, exchange its strategies at run time. The Template Method inverts the control flow, following the hollywood principle: “Don’t call us, we will call you”. The Strategy Pattern is often a black box. It allows you to replace one strategy with another without knowing its details.
- The Bridge Pattern and the Strategy Pattern have identical structures but different intents. The Bridge Pattern is a structural pattern and aims to decouple physical dependencies, the Strategy Pattern is a behavioral pattern that decouples logical dependencies and allows to injection of external implementations.
Let’s talk about the pros and cons of the Strategy Pattern.
Pros and Cons
- Algorithms are encapsulated in objects and can be exchanged during run time
- Adding new strategies is easy. You only have to implement a new strategy.
- The Strategy Pattern replaces conditional execution based on
- Callables are often lightweight implementations for strategies in C++:
The program uses the function
greater, the predefined function object
std::greater<std::string>, and a lambda expression (line 1) to sort a
std::vector<std::string> in descending way. The callables are, in this example, binary predicates.
- Clients must know and choose the right strategy
- The number of objects (strategies) increases heavily
I presented in my last posts the following Design Patterns from the seminal book “Design Patterns: Elements of Reusable Object-Oriented Software“.
The ones listed here are the ones most relevant in my past. In my next post, I will write about idioms in C++. An idiom is an implementation of an architecture or design pattern in a concrete programming language.