Singleton Design Pattern

Janvi Arora
4 min readMar 3, 2023

--

Singleton pattern is a design pattern that restricts the instantiation of a class to a single object. It ensures that only one instance of the class exists throughout the lifetime of an application and provides a global point of access to that instance. In Swift, you can implement the Singleton pattern using a combination of a private initializer, a static instance variable, and a static accessor method.

Here’s an example implementation of a Singleton in Swift:

class MySingleton {
static let sharedInstance = MySingleton()
private init() {}

func doSomething() {
print("Doing something...")
}
}

Singleton pattern is a design pattern that restricts the instantiation of a class to a single object. It ensures that only one instance of the class exists throughout the lifetime of an application and provides a global point of access to that instance. In Swift, you can implement the Singleton pattern using a combination of a private initializer, a static instance variable, and a static accessor method.

Here’s an example implementation of a Singleton in Swift:

class MySingleton {
static let sharedInstance = MySingleton()
private init() {}

func doSomething() {
print("Doing something...")
}
}

In this implementation, the MySingleton class has a private initializer to prevent external instantiation of the class. The sharedInstance static variable is initialized with a single instance of the class. This instance is created only once when the class is first accessed. The doSomething method can be called on the shared instance of the class to perform some action.

To use the Singleton class in your code, you can access the shared instance using the sharedInstance static variable:

MySingleton.sharedInstance.doSomething()

This will call the doSomething method on the shared instance of the MySingleton class.

Note that the Singleton pattern should be used judiciously, as it can introduce a global state into your code and make testing more difficult.

In the Singleton pattern, the init() method is often declared as private or file-private, so that only the Singleton class itself can create an instance of the class. This prevents other parts of the code from creating new instances of the Singleton class and ensures that only one instance of the class exists throughout the entire lifetime of the program.

In the example implementation of the Singleton pattern we discussed earlier, the init() method is marked as private. This means that only the shared property of the class can create an instance of the class.

Here’s the code for the private init() method in the example:

private init() {
// Initialization code here.
}

In this case, the init() method is empty because there is no initialization code that needs to be executed when creating the Singleton instance. However, you can add any initialization code that is necessary for your specific use case.

It's worth noting that the private init() method ensures that no other part of the code can create an instance of the Singleton class using the regular initializer syntax (i.e., MySingleton()). Instead, you must use the shared property of the Singleton class to access the single instance of the class (i.e., MySingleton.shared).

NOTE: URLSession also uses singleton pattern, as we can use it’s shared instance as:

URLSession.shared

Advantages of using singleton pattern:

  1. Global Access: A singleton object provides a global point of access to a particular instance, so any other object in the application can easily access its methods and properties. This makes it easy to manage shared resources across the application.
  2. Single Instance: Singleton pattern ensures that only one instance of a class is created, and that instance is shared across the application. This prevents multiple objects from being created, which can be useful in scenarios where it is important to ensure consistency in the application’s state.
  3. Thread Safety: Since a singleton object is only instantiated once, it eliminates the possibility of race conditions that may occur in multithreaded applications where multiple objects are instantiated and accessed by multiple threads.
  4. Memory Management: Since a singleton object is only instantiated once, it can help to reduce the memory footprint of an application. This can be useful in scenarios where memory usage is a critical factor, such as in mobile applications.
  5. Encapsulation: A singleton object provides a level of encapsulation for the functionality it provides. This means that the details of how the functionality is implemented can be hidden from other parts of the application, making it easier to maintain and modify the codebase.

Disadvantages of using singleton pattern:

  1. Global State: Singleton pattern can create a global state for the application, which can be accessed and modified from any part of the code. This can make it harder to understand and maintain the code as the number of dependencies and interactions increase.
  2. Difficult to Test: Singleton pattern can make the code difficult to test. Since the singleton instance is global, it cannot be easily replaced with a mock object for testing purposes. This can lead to increased coupling between classes and make it harder to test the code in isolation.
  3. Can Create Race Conditions: In a multi-threaded environment, singleton pattern can create race conditions if multiple threads try to access or modify the same instance of the singleton at the same time. This can lead to unpredictable behaviour and bugs.
  4. Can Lead to Overuse: Singleton pattern can be overused, leading to unnecessary complexity in the code. It is important to carefully consider whether a singleton is the best design pattern to use in a given situation.
  5. Hard to Subclass: Since the constructor of a singleton is private, it can be difficult to subclass the singleton for testing or customization purposes. This can make it harder to extend the functionality of the singleton in the future.

--

--

No responses yet