Book Image

Swift 2 Design Patterns

By : Julien Lange
Book Image

Swift 2 Design Patterns

By: Julien Lange

Overview of this book

Table of Contents (15 chapters)
Swift 2 Design Patterns
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

The strategy pattern


When you need to change part of an object's algorithm at runtime, without modifying the client, the strategy pattern is the appropriate pattern to be used.

It removes an algorithm from its host class and moves it to a separate class. The algorithm part that can change is the strategy. Every strategy uses the same interface. The class using the strategy pattern delegates the treatment of the algorithm to the strategy.

Roles

The strategy pattern is used to create an interchangeable family of algorithms from which the required process is chosen at runtime.

The algorithm changes don't affect the client part. This pattern can be used in the following cases:

  • The behavior of a class can be implemented by different algorithms where some of them are better in terms of execution time or memory consumption

  • Choosing the appropriate algorithm with if conditions instruction complexify the code

  • A system has similar classes where only the behavior changes; in this case, the strategy pattern...