Understanding Singleton Design Pattern in Swift
First of all, it is necessary to understand what Design Patterns are. Here is my medium article link for the same.
It covers the intro to Design Patterns in very concise way. Please do check it in case you are completely beginner to design patterns.
Singleton is a design pattern that ensures a class can have only one object. Hence, Singleton pattern restricts a class to only one instance.
There is a high chance that you have already used Singleton pattern in Swift. The following examples may look similar if you have worked with Apple’s framework.
// Shared URL Session
let sharedURLSession = URLSession.shared
// Default File Manager
let defaultFileManager = FileManager.default
// Standard User Defaults
let standardUserDefaults = UserDefaults.standard
// Default Payment Queue
let defaultPaymentQueue = SKPaymentQueue.default()
Before proceeding further, it is important to know the role of static variables
.
Static variables are those variables whose values are shared among all the instance or object of a class. When we define any variable as static, it gets attached to a class rather than an object.
How to implement Singleton Class?
Let us create class Singleton
that has a static variable shared
and a function businessLogic
that performs some task for us.
class Singleton {
static let shared = Singleton()
// yes, private init!!!
private init() {}
func businessLogic() {
// some business logic
print("Business Logic Successfully implemented")
}
}
Note that we have used private
initialiser for init(). Now, we write the code to use Singleton
Singleton.shared.businessLogic()
The output is as expected, it runs the function businessLogic
. We see Business Logic Successfully implemented printed in the console.
Now, let us try to create another instance of Singleton
class.
let anotherInstance = Singleton()
Xcode IDE shows an error straight away stating:
Note that we have used private
initialiser for init() in our Singleton
class. So, if you try to create a new instance of class Singleton
it will throw an error. Hence, the principle of Singleton pattern
(only one instance of a class) is verified.
Singleton Pattern Pros
- There is only one instance of a class, we can be certain of that. There is only one instance of a class, we can be certain of that.
- One time initialisation
Singleton Pattern Cons
- The singleton object has global access. This means the singleton object can be access from anywhere in the project.
- Singleton Pattern violates Single Responsibility Principle
If you found this article helpful, kindly share this story, follow me on medium and give applaud 👏. Thank You!