Summer SALE

Decorator in Swift

Decorator is a structural pattern that allows adding new behaviors to objects dynamically by placing them inside special wrapper objects, called decorators.

Using decorators you can wrap objects countless number of times since both target objects and decorators follow the same interface. The resulting object will get a stacking behavior of all wrappers.



Usage examples: The Decorator is pretty standard in Swift code, especially in code related to streams.

Identification: Decorator can be recognized by creation methods or constructors that accept objects of the same class or interface as a current class.

The following examples are available on Swift Playgrounds.
Kudos to Alejandro Mohamad for creating the Playground version.

Decorator in Other Languages

Decorator in C# Decorator in C++ Decorator in Go Decorator in Java Decorator in PHP Decorator in Python Decorator in Ruby Decorator in Rust Decorator in TypeScript