Design Patterns with Swift: Quick look at a Strategy Pattern

iOS, swift, design patterns, strategy pattern 1 min edit

Image Title

Let’s take a quick look at one of the design patterns that should help us to write a good Object-Oriented code. The basic assumption of Strategy Pattern is that you can define many implementations that will conform to the protocol.

Take a look at a simple example that can be used on iOS applications.

Firstly, create a protocol which contains a method. In our case it will be:

Define protocol

Create strategies

Ok, most of the iOS apps use an UIImage to represent images in applications. The UIImage instance can be used to produce two different data representations of image UIImagePNGRepresentation and UIImageJPEGRepresentation. Let’s create classes that handle this stuff.

Now, as you can see - both classes conforms to the ImageRepresentation protocol but they differ in implementation. Each class represents a different strategy.

Create client

The last thing - creating a client that uses one of the ImageRepresentation strategies.



The cool thing about Strategy Pattern is that we can change our strategy at runtime. While using the Strategy Pattern we definitely conform to “Open-Close” SOLID principle. Our client is open for extensions by changing the strategy without changing the client implementation(close for modification). Also, the ImageRepresenter with Strategy Pattern included will be easiest to test.

Let’s think how the above code could look like without Strategy Pattern:

Using Switch

or using multiple functions

Both of these solutions definitely are not on the same line with CleanCode. Also, it might be hard to maintain that kind of code. The switch statement can grow with the next cases - what if we had to handle a 10, 20 or 100 strategies? The second one using multiple functions is also bad because we will continue duplicating the similar methods to handle each case. This few arguments should convince you to use Strategy Pattern. And last but not least, this two examples breakes the Open-Close principle.

This article is cross-posted with my blog