The Decorator Design Pattern
The Decorator pattern dynamically adds behaviors and responsibilities to an object without modifying its code. It’s an alternative to subclassing where you modify a class’s behavior by wrapping it with another object.
In Swift there are two very common implementations of this pattern: Extensions and Delegation.
Extensions
Adding extensions is an extremely powerful mechanism that allows you to add new functionality to existing classes, structures or enumeration types without having to subclass. What’s also really awesome is you can extend code you don’t have access to, and enhance their functionality. That means you can add your own methods to Cocoa classes such as UIView and UIImage!
For example, new methods that are added at compile time can be executed like normal methods of the extended class. It’s slightly different from the classic definition of a decorator, because a extension doesn’t hold an instance of the class it extends.
How to Use Extensions
Where will the album titles come from?
Album
is a Model object, so it doesn’t care how you present the data. You’ll need some external code to add this functionality to the Album
class, but without modifying the class directly.
You’ll create a extension that will extend the
Album
class; it will define a new method that returns a data structure which can be used easily with UITableView
.
The data structure will look like the following:
To add a Extensions to
Album
, navigate to File\New\File… and select the iOS > Source > Swift File template, and then click Next. Enter AlbumExtensions
and click Create.
Go to AlbumExtensions.swift and add the following extension:
extension Album { func ae_tableRepresentation() -> (titles:[String], values:[String]) { return (["Artist", "Album", "Genre", "Year"], [artist, title, genre, year]) } } |
Notice there’s a
ae_
at the beginning of the method name, as an abbreviation of the name of the extension: AlbumExtension
. Conventions like this will help prevent collisions with methods (including possible private methods you might not know about) in the original implementation.
Note: Classes can of course override a superclass’s method, but with extensions you can’t. Methods or properties in an extension cannot have the same name as methods or properties in the original class.
Consider for a moment how powerful this pattern can be:
- You’re using properties directly from
Album
. - You have added to the
Album
class but you haven’t subclassed it. If you need to sub-classAlbum
, you can still do that too. - This simple addition lets you return a
UITableView
–ish representation of anAlbum
, without modifyingAlbum
‘s code.
This is a very nice article. thank you for publishing this. i can understand this easily.!!..iOS Swift Online Course
ReplyDelete