Design Patterns in iOS — Singleton

Singleton Pattern Singleton Pattern: Ensures a class has only one instance and provides a global access point to it. The Singleton is probably the simplest form among all design patterns. The intent of this pattern is to make exactly one object of a class serve as the sole instance in the system. Class Diagram When to Use - A class must have exactly one instance, and that instance must be accessible from a well-known access point, such as a factory method. - The sole instance should be extensible only through subclassing, and clients should be able to use the extended object without modifying their code. Advantages: 1. Provides controlled access to the sole instance. 2. Since only one object exists in system memory, it conserves resources. For objects that are frequently created and destroyed, the Singleton pattern can noticeably improve system performance. 3. Because the singleton class controls the instantiation process, the class can be more flexibly adjusted regarding how instantiation happens. Disadvantages: 1. Because there is no abstraction layer in the Singleton pattern, extending a singleton class is quite difficult. 2. The singleton class carries too many responsibilities, which to some extent violates the Single Responsibility Principle. Usage First, let's look at a C++ implementation: In Objective-C: The implementation above has issues. First, if a client initializes the singleton using a different method, multiple instances could be created. Also, this implementation is not thread-safe. An improved version: Of course, writing this boilerplate for every singleton is too tedious. We can extract it into a macro: Usage: Singleton in Cocoa The most common singleton class in Cocoa is . It provides a centralized point for controlling and coordinating the application. Each application has one and only one instance. It is created as a singleton object when the application launches via the function. Afterward, the same instance can be accessed through the class method. The object handles many housekeeping tasks for the application, including initial routing of incoming user events and dispatching action messages from to the appropriate target objects. It also maintains a list of all objects open in the application. The application object is always assigned a object, which is notified of important runtime events — such as app launch, low memory warnings, app termination, and background process execution in iOS — giving the delegate a chance to respond appropriately. , , and others are also common singleton implementations. Summary Whenever an application needs a centralized class to coordinate its services, that class should produce a single instance. Code All the code in this article can be found on my GitHub .