Sobes.tech
Junior — Middle

How to create a class that is guaranteed to have only one instance without using the Singleton pattern?

sobes.tech AI

Answer from AI

To create a class with a guaranteed single instance without using the Singleton pattern, you can use an approach with creating an instance in advance and providing access to it through a static property or method. For example, in Swift (iOS), you can do it like this:

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

Here, sharedInstance is the only instance of the class, and the init() constructor is made private so that other instances cannot be created from outside.

If you cannot use the Singleton pattern but need to limit the creation of instances, you can:

  • Make the class final and the constructor private
  • Create a factory method that controls the creation of instances and always returns the same object

Example of a factory method:

class MyClass {
    private static var instance: MyClass?
    private init() { }

    static func getInstance() -> MyClass {
        if instance == nil {
            instance = MyClass()
        }
        return instance!
    }
}

Thus, the class guarantees the creation of only one instance without using the classic Singleton pattern.

How to create a class that is guaranteed to have only… - sobes.tech