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

Using it like:

SwiftKotlin

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. :]

Share:

administrator

Aaqib is an enthusiastic programmer with the love of Swift and anything that looks like Swift i.e Kotlin. He loves writing code in Swift, and exploring new technology and platforms. He likes to listen to old music. When he is not writing code, he's probably spend his time watching movies, tv-shows or anime, or either doing some research for writing the next article. He started Kode Snippets in 2015.

1 Comment

Leave a Reply

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