Pro Design Pattern in Swift. Adam Freeman. Apress.
Patterns' short descriptions from the book. Just to remember. The definition quoted (in green color) from the book of GOF.
Creating Patterns
“Creational design patterns abstract the instantiation process.They help make a system independent of how its objects are created,composed, and represented. A class creational pattern uses inheritance vary the class that's instantiated, whereas an object creationalpattern will delegate instantiation to another object.”The Object Template Pattern
The object template pattern uses a class or struct to define a template from which objects are created. When an application component requires an object, it calls on the Swift runtime to create it by specifying the name of the template and any runtime initialization data values that are required to configure the object. The benefit of this pattern is that it provides the basic tools that can be used to break tightly coupled components apart, allowing a public API to be presented to the consumers of an object and a hidden private implementation.
The Prototype Pattern
“Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype. ”Scope: Object. Aspect(s) That Can Vary: class of object that is instantiated
The Singleton Pattern
“Ensure a class only has one instance and provide a global point of access to it.class var server:BackupServer { struct SingletonWrapper { static let singleton = BackupServer(name:"MainServer"); } return SingletonWrapper.singleton; }
Scope: Object. Aspect(s) That Can Vary: the sole instance of a class
The Factory Method Pattern
“Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclass.”The factory method pattern selects an implementation class to satisfy a calling component’s request without requiring the component to know anything about the implementation classes or the way they relate to one another. This pattern consolidates the logic that decides which implementation class is selected and prevents it from being diffused throughout the application. This also means that calling components rely only on the top-level protocol or base class and do not need any knowledge about the implementation classes or the process by which they are selected.
Scope: Class. Aspect(s) That Can Vary: subclass of object that is instantiated
Abstract Factory Pattern
“Provide an interface for creating families of related or dependent objects without specifying their concrete classes.”The abstract factory pattern allows a calling component to create a group of related objects. The pattern hides the details of which classes are used to create the objects and the reason why they were selected from the calling component. This pattern is similar to the factory method pattern. The calling component doesn’t know which classes are used to create the objects or why they were selected, which makes it possible to change the classes that are used without needing to change the components that consume them.
Scope: Object. Aspect(s) That Can Vary: families of product objects.
The Builder Pattern
“Separate the construction of a complex object from its representation so that the same construction process can create different representations.”
The builder pattern puts the logic and default configuration values required to create an object into a builder class. This allows calling components to create objects with minimal configuration data and without needing to know the default values that will be used to create the object. This pattern makes it easier to change the default configuration values used to create an object and to change the class from which instances are created.
The calling component knows what is required—a burger with no ketchup, for example—but it doesn’t know how to create it. The builder class knows how to create a burger and knows the default configuration, but it doesn’t know what the customer wants for any specific order. The builder pattern brings the “what” and the “how” together without letting the calling component become tightly coupled to the objects it requires.
The most commonly used example of the builder pattern can be found in the NSDateComponents class in the Foundation framework.
Scope: Object. Aspect(s) That Can Vary: how a composite object gets created
The Structural Patterns
“Structural patterns are concerned with how classes and objects are composed to form larger structures.Structural class patterns use inheritance to compose interfaces or implementations.”
The Adapter Pattern
“Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.”The adapter pattern allows two components with incompatible APIs to work together by introducing an adapter that maps from one component to the other.
This pattern allows you to integrate components for which you cannot modify the source code into your application. This is a common problem when you use a third-party framework or when you are consuming the output from another project.
Scope: Class. Aspect(s) That Can Vary: interface to an object
The Bridge Pattern
“Decouple an abstraction from its implementation so that the two can vary independently.”The bridge pattern separates an abstraction from its implementation so that either can be changed without a corresponding change in the other. More commonly, the bridge pattern is used to resolve a problem known as an exploding class hierarchy, which usually arises through repeated but poorly thought-out refactoring and requires
an ever-increasing number of classes to add new features to the application.
When the bridge pattern is applied to the exploding class hierarchy problem, the benefit is that adding a new feature to the application requires only a single class. More broadly, the pattern isolates the impact of a change when an abstraction or its implementation changes.
Use this pattern to resolve the exploding class hierarchy problem or to bridge between one API and another.
The bridge pattern separates an abstraction from its implementation so that the two can be changed independently from one another. It may sound counterintuitive, but the bridge pattern solves the exploding class hierarchy problem by creating two different hierarchies, separating the functionality that is specific to each platform from the functionality that is shared between them. A bridge class is created, which brings together both hierarchies.
Scope: Object. Aspect(s) That Can Vary: implementation of an object
The Decorator Pattern
“Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.”The decorator pattern allows the behavior of individual objects to be changed without requiring changes to the classes that are used to create them or the components that consume them.
The changes in behavior defined with the decorator pattern can be combined to create complex effects without needing to create large numbers of subclasses. The decorator solves the permutation problem by creating decorator classes, which are wrappers around the original class that change its behavior. A decorator presents the same API as the wrapped class, and decorators can wrap other decorators in order to create permutations.
Scope: Object. Aspect(s) That Can Vary: responsibilities of an object without subclassing
The Composite Pattern
“Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.”
The composite pattern allows a tree of individual objects and collections of objects to be treated consistently.
The consistency that the composite pattern brings means that components that operate on the tree structure are simpler and do not need to have knowledge of the different objects types that are in use.
Use this pattern when you have a tree structure that contains leaf nodes and collections of objects.
This pattern is applicable only to tree data structures.
Scope: Object. Aspect(s) That Can Vary: structure and composition of an object
The Façade Pattern
“Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.”The façade pattern simplifies the use of complex APIs to perform common tasks.
The complexity required to use an API is consolidated into a single class, which minimizes the impact of changes in the API and simplifies the components that consume the API functionality.
Use the façade pattern when you are working with classes that need to be used together but that don’t have compatible APIs.
Do not use the façade pattern when integrating single components into the application; use the adapter pattern instead.
The façade pattern addresses the problem by creating a class that consolidates the complexity into a single location in the application and presents a simplified API to other components:
Scope: Object. Aspect(s) That Can Vary: interface to a subsystem
The Flyweight Pattern
“Use sharing to support large numbers of fine-grained objects efficiently.”
The flyweight pattern is applied when a number of similar objects all rely on the same set of data values. Rather than create a new set of data valued for each of the objects, the flyweight pattern shares one set between all of them, minimizing the amount of memory required to store the data and the amount of work required to create them. The flyweight pattern shares common data objects between multiple calling components.
The flyweight pattern reduces the amount of memory needed to create the data objects required by the calling components and the amount of work required to create them. The impact of implementing the pattern increases with the number of calling components that share the data.
Use this pattern when you are able to identify and isolate sets of identical data objects that are used by calling components.
Do not use this pattern if there is no shared data or if the number of shared data objects is small and easy to create.
Scope: Object. Aspect(s) That Can Vary: storage costs of objects
The Proxy Pattern
“Provide a surrogate or placeholder for another object to control access to it.”The proxy pattern defines an object—the proxy—that represents some other resource, such as another object or a remote service. Calling components operate on the proxy, which in turn operates on the underlying resource.
Proxies allow close control over the way that the underlying resource is accessed, which is useful when you need to intercept and adapt operations.
Proxies are used in three main situations: to define an interface to a remote resource such as a web page or RESTful service, to manage the execution of expensive operations, and to restrict access to the methods and properties of other objects.
Scope: Object. Aspect(s) That Can Vary: how an object is accessed; its location
The Behavioral Patterns
“Behavioral patterns are concerned with algorithms and the assignment of responsibilities between objects.”
The Chain of Responsibility
“Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.”
The chain of responsibility pattern organizes sequentially a set of objects that may be able to take responsibility for a request from a calling component. The sequence of objects is referred to as a chain, and each object in the chain is asked to take responsibility for the request. The request moves along the chain until one of the objects takes responsibility or the end of the chain is reached.
The chain of responsibility allows objects that can process requests to be ordered into a preferential sequence that can be reordered, extended, or reduced without any impact on the calling component, which has no insight into the objects that comprise the chain.
Use this pattern when there are several objects that can handle a request, only one of which should be used.
The pattern is implemented correctly when the set of objects that can take responsibility for a request are arranged sequentially and each is offered the chance to take responsibility in turn. The individual objects in the chain have no knowledge of one another (other than the next link in the chain).
Scope: Object. Aspect(s) That Can Vary: object that can fulfill a request
The Command Pattern
“Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.”
The command pattern is used to encapsulate details of how to invoke a method on an object in a way that allows the method to be invoked at a different time or by a different component.
There are lots of situations in which using a command is useful, but the most common ones are supporting undo operations and creating macros.
Use this pattern when you want to allow methods to be invoked by components that otherwise have no information about the object that will be used, the method that will be invoked, or the arguments that will be provided.
Scope: Object. Aspect(s) That Can Vary: when and how a request is fulfilled
The Mediator Pattern
“Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.”The mediator pattern simplifies peer-to-peer communication between objects by introducing a mediator object that acts as a communications broker between the objects.
Instead of having to keep track of and communicate with of all of its peers individually, an object just deals with the mediator.
Use this pattern when you are dealing with a group of objects that need to communicate freely between one another. Don’t use this pattern if you have one object that needs to send notifications to a range of disparate objects; use the observer pattern
Scope: Object. Aspect(s) That Can Vary: how and which objects interact with each other
The Observer Pattern
“Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.”The observer pattern allows one object to register to receive notifications about changes in another object without needing to depend on the implementation of that object.
This pattern simplifies application design by allowing objects that provide notifications to do so in a uniform way without needing to know how those notifications are processed and acted on by the recipients.
Use this pattern whenever one object needs to receive notifications about changes in another object but where the sender of the notifications does not depend on the recipient to complete its work.
Do not use this pattern unless the sender of the notifications is functionally dependent from the recipients, such that the recipients could be removed from the application without preventing the sender from performing its work.
Scope: Object. Aspect(s) That Can Vary: number of objects that depend on another object; how the dependent objects stay up to date
The Memento Pattern
“Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later.”The memento pattern captures the complete state of an object into a memento that can be used to reset the object at a later date.
The memento pattern allows a complete reset of an object without the need to track and apply individual undo commands.
Use this pattern when there is a “known-good” point in an object’s life that you may want to return to at some point in the future.
This pattern should be used only when you need to return an object to an earlier state.
Scope: Object. Aspect(s) That Can Vary: what private information is stored outside an object, and when
The Strategy Pattern
“Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.”The strategy pattern is used to create classes that can be extended without modification, through the application of algorithm objects that conform to a well-defined protocol.
The strategy pattern allows third-party developers to change the behavior of classes without modifying them and can allow low-cost changes to be made in projects that have expensive and lengthy validation procedures for specific classes.
Use this pattern when you need classes that can be extended without being modified.
Scope: Object. Aspect(s) That Can Vary: an algorithm
The Visitor Pattern
“Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.”The visitor pattern is similar to the strategy pattern in that it allows the behavior of a class to be extended without modifying its source code or creating a new subclass, except that the visitor pattern is applied to collections of heterogeneous objects.
The visitor pattern allows new algorithms to operate on collections of heterogeneous objects without needing to modify or subclass the collection class.
The visitor pattern is useful when you want to provide collection classes as part of frameworks without requiring third-party developers to modify the source code. This pattern is also useful in projects where modifying core classes triggers expensive testing procedures.
Use this pattern when you have classes that manage collections of mismatched objects and you want to perform operations on them.
Scope: Object. Aspect(s) That Can Vary: operations that can be applied to object(s) without changing their class(es)
The Template Method Pattern
“Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.”
The template method pattern allows specific steps in an algorithm to be replaced by implementations provided by a third-party, either by specifying functions as closures or by creating a subclass.
This pattern is useful when you are writing frameworks that you want to allow other developers to extend and customize.
Use this pattern to selectively permit steps in any algorithm to be changed without modifying the original class.
Do not use this pattern if the entire algorithm can be changed. See the other patterns in this part of the book for alternatives.
Scope: Class. Aspect(s) That Can Vary: steps of an algorithm





























