The Decorator Design Pattern in Swift

Add to it!

Steven Curtis
2 min readDec 4, 2022
Photo by Spacejoy on Unsplash

Difficulty: Beginner | Easy | Normal| Challenging

This article has been developed using Xcode 11.5, and Swift 5.2.4

Prerequisites:

Terminology:

Design Pattern: a general, reusable solution to a commonly occurring problem

Rather than subclassing (which follows from the principle that we should favour composition over inheritance)

The Decorator Design Pattern in Swift

Essentially decorators act as a middle man, intercepting calls to a core object and providing customised behaviour to the client.

This means the design pattern is useful if

  • The core object needs to be wrapped for the purpose of testing
  • The core object cannot be modified directly

The Detail

The decorator allows adding behaviour and responsibility to an object without modifying code. This is commonly implemented in Swift, and when used clients are not aware if they are using a decorator or core object to access functionality.

--

--