Sobes.tech
Junior — Middle

What is the main task and principle of the Singleton pattern in programming?

sobes.tech AI

Answer from AI

The Singleton pattern guarantees that a class has only one instance and provides a global point of access to it. This is useful when you need to centrally manage state or resources, such as application settings or database connections.

Working principle:

  • The class constructor is usually private to prevent creating new instances from outside.
  • The class has a static method or property that returns the single instance, creating it upon the first call.

Example in Swift:

class Singleton {
    static let shared = Singleton()
    private init() { }

    func doSomething() {
        print("Performing an action")
    }
}

// Usage
Singleton.shared.doSomething()