What Is a Singleton?
Singleton pattern is a way to ensure that the class has only one instance and provide a global point of access to it (the Singleton instance).
Generally, we create an instance of a normal class by using the =
operator and the name of the class that we will instantiate (after =
).
class HTTPClient {
...
}
...
let client = HTTPClient()
But not if we use the Singleton pattern, since a Singleton is a class that has only one instance.
So, how to create a Singleton?
Step 1
To ensure that the class can’t be instantiated more than once from the outside world, the Singleton pattern constructor/initializer should be private
.
class HTTPClient {
private init() {}
}
Step 2
As we can’t instantiate more than once the Singleton class, we should provide a global point of access to the Singleton instance.
class HTTPClient {
private static let instance = HTTPClient()
private init() {
}
}
Step 3
Create a static function that returns the instance
.
class HTTPClient {
private static let instance = HTTPClient()
private init() {
}
static func getInstance() -> HTTPClient {
return instance
}
}
Step 4
From the outside world, create an instance with the getInstance()
function.
class HTTPClient {
private static let instance = HTTPClient()
private init() {
}
static func getInstance() -> HTTPClient {
return instance
}
}
let client = HTTPClient.getInstance()
Conclusion
The key point from what we’ve learned is that the Singleton has only one instance. We can use Singleton when we need precisely one instance of a class, and it must be accessible from a well-known access point.
For example, a class that logs messages to the console is a good Singleton candidate, as the system may require access to it from any given point. So, we only need its public API to log messages/events, and we don’t need more than one instance.