Design Pattern

1. The Singleton Pattern

The Singleton design pattern ensures that only one instance exists for a given class and that there’s a global access point to that instance. It usually uses lazy loading to create the single instance when it’s needed the first time.

The singleton pattern is very easy to overuse.

The most common reason why singleton’s are problematic is testing. If you have state being stored in a global object like a singleton then order of tests can matter, and it can be painful to mock them. Both of these reasons make testing a pain.

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.

Extension

  • Allows you to add new functionality to existing classes, structures or enumeration types without having to subclass.
  • You can even extend code you don't have access to, and enhance their functionality.
  • This means that you can add your own methods to Cocoa Classes.
  • Extensions are similar to categories in Objective-C. (Unlike Objective-C categories, Swift extensions do not have names.)

Delegation

  • Delegation is a mechanism in which one object acts on behalf of, or in coordination with, another object.
  • UITableView is greedy – it has two delegate-type properties, one called a data source, and one called a delegate.

The Observer Pattern

  • In the Observer pattern, one object notifies other objects of any state changes.
  • The objects involved don't need to know about one another - thus encouraging a decoupled design.
  • This pattern's most often used to notify interested objects when a property has changed.
  • The usual implementation requires that an observer registers interest in the state of another object. When the state changes, all the observing objects are notified of the change.

Notifications

  • Notifications are based on a subscribe-and-publish model that allows an object (the publisher) to send messages to other objects (subscribers/listeners).
  • The publisher never needs to know anything about the subscribers.
extension Notification.Name {
  static let BLDownloadImage = Notification.Name("BLDownloadImageNotification")
}

NotificationCenter.default.post(name: .BLDownloadImage, object: self, userInfo: ["imageView": coverImageView, "coverUrl" : coverUrl])

NotificationCenter.default.addObserver(self, selector: #selector(downloadImage(with:)), name: .BLDownloadImage, object: nil)

KVO

results matching ""

    No results matching ""