Singleton

Singleton

The Singleton pattern is a way to make sure that a class has only one instance and it provides single-point access to it. The pattern specifies that the class should be responsible for keeping track of its sole instance. It can further ensure that no other instance can be created by intercepting requests for creating new objects and provide a way to access the sole instance.

No alt text provided for this image

Let's simplify this with the example.

class APIService {}

        

We have one class called APIService. Now how can we make this a Singleton?

The whole point of the Singleton is to have only one instance of the class.

We can prevent people from creating APIService by making the initializer private.


class APIService {
? ? private init() {}
}
        

Now let's make it globally accessible with "static let"


class APIService {
    static let sharedInstance = APIService()
? ? private init() {}
}
        

"Static let" is constant and lazy loaded which means it is guaranteed to be lazily initialized only once, even when accessed across multiple threads simultaneously.


final class APIService {
    static let sharedInstance = APIService()
? ? private init() {}
}
        

Last but not least,

"Final" ensure that the singleton cannot be modified or subclasses.

Ta-Da!!! That's it. This is how you create Singleton. ??

---------------------------------------------------------------------------------------------------------------

No alt text provided for this image

Mutable Global Shared State


final class APIService {
    static var sharedInstance = APIService()
}
        

So this is a Mutable Global Shared State, It looks like a Singleton but it's not. Not every sharedInstance, shared or instance is a Singleton pattern. Mutable Global State is usually accessed by a 'static sharedInstance' of a class and allows the access and mutation of that reference (static var instead of static let). As it increases the chances of the system being in inconsistent states using Mutable Global Shared State can be risky. Its state can be changed from any process or thread in the app but it also offers ease of use when it comes to accessing objects throughout the system.

Conclusion

Understood the difference between Singleton & Mutable Global Shared State before using. Choose the pattern on the go while you are writing the code. Remember the limitation of each pattern and make the choices based on the problem you are trying to solve. Even if you make a wrong choice, don't worry you know where to look and fix it with the new approach. Happy Coding :)

Akshay Tiwari

Everything every day all at once

3 年

Really good stuff.. You should write more often.

要查看或添加评论,请登录

Sudhir Gadhvi的更多文章

社区洞察

其他会员也浏览了