As the name suggests itself. Singleton means something occurring or existing singly and not in multiple forms or states. In terms of programming. An instance which is created only once and can be accessed throughout the lifecycle of a program or application. A Singleton is responsible of creating its own instance. A Singleton class holds a static instance of itself. A client uses that static instance of that Singleton class to access further of its properties or methods. Singleton Design Pattern is a type of Creational Design Pattern.

Class Diagram

Implementation

Creating a Singleton is pretty straight forward.

SwiftKotlin
class Singleton {
    
    static let shared = Singleton()
    
    private init() {}
    
    var someProperty: String = "Hello, world!!!"
    
    func doSomething() {
     print(someProperty)   
    
    }
}
class Singleton private constructor() {
    
    companion object {
        var getInstance = Singleton()
    }
    
    var someProperty: String = "Hello, world!!!"
    
    fun doSomething() {
    println(someProperty)
    
    }
}

Using it like:

SwiftKotlin
Singleton.shared.someProperty
Singleton.shared.doSomething()
Singleton.getInstance.someProperty
Singleton.getInstance.doSomething()

Pros

Due to Singleton having a private constructor. It avoids creation of multiple instances and also stops a client from instantiating an instance of it from the outside. It uses lazy initialization. It is globally accessible. It provides a shared resource to every object that is using it. It can hold data over the life cycle of an application or program.

Cons

It’s difficult to write Unit test of a Singleton class because the class cannot be mocked until or unless the constructor is made public. Dependency Injection through the constructor is not possible because the instance is created within the class. Mutability is another concern of using a Singleton. Since a Singleton is globally accessible, values inside can be changed by another thread at a given time and can lead to anomalies.

Conclusion

Singleton Pattern has its own benefits but trying to use it on each of your problems is not a good idea. While using it inside a class try to inject it as a dependency to make use of it. Since it holds a static reference to the class itself. Over using it might lead to memory leaks or uncontrollable mutability issues.

If you have any questions please feel free to leave them in the comment section below. :]

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *