Design Patterns on iOS using Swift — Part 1/2

As you develop this application, you will become familiar with the most common Cocoa design patterns:

  • Create type (Creational) : singleton mode (Singleton)
  • Structured (Structural) :MVC, decorator mode (Decorator), adapter mode (Adapter), appearance mode (Facade)
  • Behavior type (Behavioral) : Observer mode (Observer), Memo mode (Memento)

The king of design patterns – MVC

Model-view-controller (MVC) is one of the building blocks of Cocoa and is undoubtedly the most commonly used design pattern. It classifies objects according to their role in the application and encourages clear separation of role-based code.

The three roles are:

  • model:Save the application (applicationData object and defines how to operate on it. For example, in your application (application),ModelisAlbumStructure that you can use inAlbum.swiftFind it in. Most applications will have multiple types as part of their model
  • View:To be responsible for themodelVisually represented objects and controls with which users can interact; Basically, all of themUIView derivedThe object. In your application,ViewbyAlbumViewIndicates that you canIn AlbumView. SwiftFind it in.
  • ViewController:The controller is the intermediary that coordinates all the work. It accessesmodelAnd use itviewShows, listens for events and manipulates data as needed. You can guess which oneclassIs yourcontroller? That’s right:ViewController.

The communication between View and Model can be best described by Controller, as shown in the following figure:

The singleton pattern

final class LibraryAPI {
  / / 1
  static let shared = LibraryAPI(a)/ / 2
  private init(a){}}Copy the code

Avoid abusing singletons

1. Global status// A singleton can be used anywhere without explicitly declaring dependencies. Mainly used in testing, need to pay special attention to the order of the test
2. The life cycle of the object// Singletons should only be used to hold global state and should not be bound to any scope. If the scope of these states is shorter than the life cycle of a full application, then the state should not be managed using singletons.
Copy the code

In cases where singletons are unavoidable, you should consider using singletons plus, where objects can still create instance objects themselves

The Facade Design Pattern

** Facade design pattern: ** Provides a single interface for complex subsystems, exposing a single unified API rather than exposing consumers to a set of classes and their APIs.

Usage scenario: When componentizing, a unified API extraction is performed in a Module, or when a third-party library is referenced, a layer of API-based encapsulation can be performed. Load the use of web images in places like SDWebimage or Kingfisher. The user does not need to know how the internal logic is invoked.

The following chart illustrates the concept:

Users of the API need not be aware of the intricacies of the API. This pattern is ideal when you use a large number of classes, especially when they are complex to use or difficult to understand

The Decorator Design Pattern

Decorator pattern: ** Dynamically adds behaviors and responsibilities to objects without modifying their code. It is an alternative to subclassing, modifying the behavior of a class by wrapping it with another object.

In Swift, there are two very common implementations of this pattern: Extensions and Delegation

Extensions

Adding extensions is a very powerful mechanism that allows you to add new functionality to existing classes, structs, or enumerated types without subclassing. Even more impressive, you can extend code that you don’t have access to and enhance its functionality. This means you can add your own methods to Cocoa classes, such as UIView and UIImage!

Note: Classes can of course override methods of their parent classes, but not when using extensions. A method or property in an extension cannot have the same name as a method or property in the original class.

Delegation

Another implementation of the Decorator design pattern is a delegate, which is a mechanism in which one object represents or works in collaboration with another object.

The Adapter Pattern

Adapters allow classes with incompatible interfaces to work together. It wraps itself around an object and exposes a standard interface to interact with that object.

If you’re familiar with the adapter pattern, you’ll notice that Apple implements it in a slightly different way — Apple uses protocols to do its job. You may be familiar with protocols such as UITableViewDelegate, UIScrollViewDelegate, NSCoding, and NSCopying. For example, using the NSCopying protocol, any class can provide a standard replication method.

Observer model

In the Observer pattern, one object notifies the other of any state changes. The objects involved do not need to know each other – thus encouraging separate design. This property is most often used to notify objects of interest when a property changes.

The usual implementation requires the observer to register interest in the state of another object. When the state changes, all observed objects are notified of the change.

Cocoa implements the observer mode in two ways: Notifications and key-value Observing (KVO)

Factory Pattern (The Memento Pattern)

Class cluster

The Memento Pattern

** Memo pattern: ** captures and externalizes the internal state of an object. In other words, it can keep your stuff somewhere. Later, this externalization state can be restored without violating encapsulation; That is, private data is still private.