The Strategy Pattern

The strategy pattern gives you the possibility to change the concrete implementation of an algorithm any time without breaking the rest of your code. Furthermore, it is a very good example of using polymorphism.

Hint: This post has been updated to Swift 3

The Idea

Imagine you want to use an algorithm, that solves a concrete problem, but you do not want do be dependent on a concrete implementation of this algorithm. A reason for that could be that you know that there will be a much more efficient algorithm in the future. Or, you want to be able to choose from algorithms with different properties. Sometimes you want for example a quicker implementation and at another time a more precise one.

To be able to change the implementation of the algorithm without breaking your whole code, there is the so called strategy pattern. First, you need to declare a protocol (in other programming languages called interface) for the algorithm. Then you instantiate an object of a class, that implements that protocol. However, this instantiation is of the protocol type, so that in the following it doesn’t matter which concrete implementation you are using:



Imagine that you have a class called  ArrayStatistics, that calculates some statistical values for an integer array. For that, the class needs a sorting algorithm. For the class to be able to use different implementations of the sorting algorithm, we define the  ArraySort protocol. Furthermore, we develop two concrete implementations of the sorting algorithm:  SimpleSort and  BubbleSort. Now we are able to set the actual implementation of the algorithm from outside of the class  ArrayStatistics:

That means that the sorting algorithm of  ArrayStatics can be changed without touching the code inside of ArrayStatistics! We just need to create an instance of the other sorting class:


The strategy pattern is very effective for writing code, that depends not on a concrete implementation of an algorithm.


Image: @ solarseven /

Book Tip

Big Nerd Range Guide: iOS Programming: Excellent introduction to iOS development. Some programming experience is recommended.