Swift

Strategy Pattern – Swift

Strategy Pattern – Swift

Reading Time: 3 minutes

This time we will try to create an example of the Strategy Pattern. Strategy Pattern is one of the 23 classic OOP design patterns defined inĀ Design Patterns: Elements of Reusable Object-Oriented Software. This pattern is used usually to alter between few “strategies” and defers this decision to be made in run-time. Usually a good example for Strategy Pattern in use is for hosing between algorithms based on client’s decision. Algorithms could be different sort algorithms, validation algorithms, etc.

Example – Validation

This example written in Swift language is written to demonstrate how easy is to choose a strategy, in compile time but even better, in run-time. We will create validation strategies to make it easier to choose between validation algorithms on strings input.

Diagram

Lets describe in a short how would we use the strategy pattern, easiest way is to follow this diagram:

In short, each part is responsible for:

Context

  • Holds the actual ConcreteStrategy object, defined by the client, but exposes only the Strategy class API.
  • Can instantiate a default Strategy.
  • Can expose its data to the concrete strategies (not in this example)

Strategy

  • Defines the interface of the strategies, or in our example is just swift protocol.

ConcreteStrategy

  • Implements the actual algorithm

Code

After I read again my example I realize that a better example would not be to choose between 2 types of validation (Email, Password) but between 2 algorithms of the same validation type. But you can see here how robust this design pattern is, you can use it however your problem domain forces you. (I will fix it soon)

If you want to watch for more design patterns examples I wrote, please visit here.

Cheers,