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.
Creating a Singleton is pretty straight forward.
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:
Singleton.shared.someProperty Singleton.shared.doSomething()
Singleton.getInstance.someProperty Singleton.getInstance.doSomething()
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.
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.
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. :]
This article covers some important things you must know when you are considering a move…
What is Unit Testing? In its simplest term, unit testing is testing a small piece…
In this article, you will learn about a type of Creational Design Pattern which is…
In this tutorial, you will go through the use of targets to achieve two separate…
In this article, you will learn about a type of Structural Design Pattern which is…
Design Patterns are an important part of a Software design. In this article you'll learn…
View Comments