Recently I gave a talk at NSCoder Night Madrid about the Strategy pattern. People loved it! I felt that our community will benefit from this knowledge too. So in this guide, I will explain Strategy pattern for iOS and provide some examples.

What is it?

Firstly we should define this pattern. In Wikipedia, it is defined as follow:

In computer programming, the strategy pattern is a behavioral software design pattern that enables selecting an algorithm at runtime. Instead of implementing a single algorithm directly, code receives run-time instructions as to which in a family of algorithms to use.

🤯 ⁉️ This definition is very theoretical, so I think we could define it easier:

Encapsulates algorithms in classes, making them reusable and interchangeable at runtime.

Classification

The design patterns are classified into 3 categories according to their objectives:

Creational

Structural

Behavioural

Yes, Strategy pattern is a behavioural pattern because it’s related to the behavioural of the objects. Easy, right?

When we should use it

There are many cases when we can use it. Let’s talk about three very specific scenarios in which we can see a clear value of the Strategy pattern.

1️⃣ Different ways to do the same

When you need to do the same thing in your code by different ways, it’s a clear example that you could use it.

2️⃣ Instead of inheritance

If you need to extend the functionality of a class and for doing this, you need to create a new class who inherits from it.

3️⃣ Alternative to if/else blocks

This is my favourite. Sometimes, if you look at a class, you can see that it has too much if/else or switch blocks, I mean, conditional blocks. This is a sign that this class has more responsibilities than it should. Using a Strategy pattern would help you distribute them.

Real Example

Imagine we need to create a Logger class, who prints a message in the console. Also, this class allows you to print stylized messages: lowercase, uppercase and capitalized. So, a possible implementation could be something like this:

Then, we would have an enum to specify which styles are available and a function log with a switch block inside to print the message in the console in the different styles.

Not bad, but really printing the message using different styles is the responsibility of the logger? What happens if we have twenty styles instead of only three? We should modify this class by adding the new styles inside the enum and the log function as well. 😅

According to the scenarios that we saw previously, this could be a good example where Strategy pattern could help us.