Sobes.tech
Junior

What is a singleton?

sobes.tech AI

Answer from AI

Singleton is a creational design pattern that guarantees a class has only one instance and provides a global point of access to it.

Advantages:

  • Control over the single instance.
  • Global access point.
  • Lazy initialization (if implemented).

Disadvantages:

  • Violates the single responsibility principle.
  • Makes testing difficult.
  • Can cause issues in multithreaded environments without synchronization.

Typical implementation in Swift:

class Singleton {  
    // Static constant to hold the single instance
    static let shared = Singleton()  

    // Private initializer to prevent creation of other instances
    private init() {  
        // Additional setup if needed  
        print("Singleton instance created")  
    }  

    // Example singleton method  
    func doSomething() {  
        print("Singleton is doing something")  
    }  
}  

Usage:

// Access the single instance via the static property
let instance = Singleton.shared  
instance.doSomething()  
  
// Attempting to create another instance will cause a compile error
// let anotherInstance = Singleton() // Error!  
What is a singleton? — iOS - sobes.tech