Decorator Pattern in Swift

For some reason(legacy code, library code, etc…) you can not modify an object’s code but you want to alter its behaviour and do not want to use inheritance, then this pattern might help you.

As an example, let’s have a class named DefaultButtonStyler to style our buttons:

Later, you needed to have a button with corner radius and you can not modify DefaultButtonStyler. Then, at this point you can create a decorator class to alter the existing styling functionality:

In initialization, CornerRadiusButtonStyler takes a decoratee object, wraps it and in style(_:) function, it alters its behaviour by adding a cornerRadius to the button.

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

SwiftUI Custom View Modifiers

How To Create a Framework With Carthage Support

How to build and use an XCFramework

The fourth round of public beta of iOS 15 is here. What changes do you know?

How to use xcassets for alternative icons

iOS App Development: Publishing a CocoaPods library with Swift that turns pictures to grayscale.

RxSwift Memory Leak While Passing Functions to Operators

The new MacBook Pros and their notch

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Hasancan Akgündüz

Hasancan Akgündüz

iOS Developer

More from Medium

Swift Closures

A Beginner’s guide to becoming an iOS Developer

Page Object Pattern for iOS UI Testing

Threads & Concurrency In Swift

Multiple Threading swift