Swift: Singleton Pattern
In this article, we are going through a creational design pattern, Singleton.
What is Singleton?
A pattern is called Singleton when it satisfies the below conditions:
- Class should create its own single private instance.
- Class shouldn't allow creating instances from outside.
- Others can access the class, only through the instance created within the class.
Normally, this is how a singleton looks in any other language.
class User {
// 1
private let shared = User()
// 2
private init() { }
// 3
static func getInstance() -> User {
return shared
}
}
//MARK:- USAGE
User.getInstance()
From the above code,
- You are creating the single private instance
sharedof the class User. - You are adding the private access modifier to the
init()method so that no other instance can be created by others. - Exposing the instance - Creating the getter method
getInstanceand returning the privately initializedsharedobject, so that others could use this to access the properties inside the User class.
Alas, the Singleton is created, But there is a way to improve the above code. Since we are coding in Swift, You can declare the shared instance using the static property, so you don't need to have a separate method for exposing the instance. Here's the code for Swifty Approach.
class User {
// 1
static let shared = User()
private init() { }
}
//MARK:- USAGE
User.shared
The only change that is performed in the above code is the private instance is changed to a static instance in order to achieve a swiftier approach.
Hope you enjoyed reading this, we can explore more about the design patterns in the following articles.
Happy Coding!!!