Singleton Design Pattern

emre gürses
2 min readFeb 4, 2023

What is a singleton design pattern?

The Singleton design pattern is a creational pattern in software engineering that restricts a class to have only one instance, while providing a global point of access to this instance for the entire system. It ensures that a class has only one instance, while providing a way to access this instance from any part of the program, without the need to pass the instance as an argument to each function. This is useful in cases where only a single instance of a class should exist, for example, to represent a database connection, a logging service, or an application configuration.

final class SessionKeeper {
static let shared = SessionKeeper()

private init() {
// Intensionally unimplemented
}
}

In this example, the SessionKeeper class has a static constant shared that is an instance of the class. The private init() method ensures that the class can only be instantiated within the class itself, thus enforcing the singleton pattern. Also ve declare final keyword top of the SessionKeeperthat ensure somehow this class will not inherent.

To access the singleton instance, simply use SessionKeeper.shared.

When would you use and when would you avoid singletons?

Use of Singleton pattern:

  1. When only a single instance of a class is required to control the action throughout the execution.
  2. For example, if you have a single database connection in your application, then you should use a singleton class for the database connection.

Avoid using Singleton pattern:

  1. When you want to allow multiple instances of a class to coexist, and not just one instance controlling the action.
  2. When the singleton class is tightly coupled with other classes and changing the singleton class can affect many other classes.
  3. When the singleton pattern causes tight coupling and makes unit testing difficult.
  4. Avoid singleton when modularity and testability is required

It’s important to understand that the Singleton pattern should be used judiciously and with care, as it can introduce tight coupling and make it difficult to change the implementation. It’s important to weigh the benefits of using a Singleton against its drawbacks, such as difficulty in testing, and choose an appropriate design pattern based on the needs of your system.

--

--

emre gürses

Denizbank — Intertech, Mobil Uygulama Geliştiricisi(iOS)