Decorator Pattern in Swift

Abhishek Kumar
Aug 31, 2018 · 2 min read

Decorator Pattern dynamically adds behaviours and responsibilities to an object without modifying its code. It is different from Inheritance where you can modify/override behaviours and properties of a class.

In Swift It can be done using 2 ways: — Extensions and Delegations

Extension is use for adding new behaviour and functionalities for predefined classes, structs and enums and you can achieve abstraction using combination of protocols and extensions i.e like in Java and C++ you can make abstract classes having some default behaviours.

You can add behaviourd to UIView, UIImage, and other Apple classes as well using an extensions.

Delegation is a mechanism by which one object handover it’s responsibility to other object if that other object agree to (set itself as a delegate).

UITableView is greedy – it has two delegate-type properties, one called a data source, and one called a delegate. They do slightly different things – for example, the table view asks its data source how many rows should be in a particular section, but it asks its delegate what to do when a row is selected.

You can’t expect the UITableView to know how many rows you want to have in each section, as this is application-specific. Therefore, the task of calculating the amount of rows in each section is passed on to the data source. This allows the UITableView class to be independent of the data it displays.

The UITableView object does its job of displaying a table view. However, eventually it will need some information that it doesn’t have. Then, it turns to its delegate and data source and sends a message asking for additional information.

CheckOut Singleton Pattern

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade