A method instance defining a singleton in Swift
- 2020-06-03 08:33:50
- OfStack
What is a singleton
The singleton is one of the simplest design patterns, and even some pattern gurus don't call it a pattern, but an implementation technique, because design patterns focus on the abstraction of relationships between objects, while singletons have only one object of their own.
Singleton pattern (Singleton Pattern), also known as singleton pattern, is a common software design pattern. When this pattern is applied, the class of the singleton must ensure that only 1 instance exists.
The single-instance Singleton design pattern is probably the most widely discussed and used design pattern, and probably the most frequently asked design pattern in an interview. The main purpose of this design pattern is that only one instance of a class can occur in the entire system. There are certain things you can do, such as global configuration information for your software, or an Factory, or a master class, etc.
How do I create singletons in swift
There are two ways to create singletons in swift
Global variables
let sharedNetworkManager = NetworkManager(baseURL: API.baseURL)
class NetworkManager {
// MARK: - Properties
let baseURL: URL
// Initialization
init(baseURL: URL) {
self.baseURL = baseURL
}
}
This global variable is used for reference
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
print(sharedNetworkManager)
return true
}
Static properties and ways to privatize methods
class NetworkManager {
// MARK: - Properties
private static var sharedNetworkManager: NetworkManager = {
let networkManager = NetworkManager(baseURL: API.baseURL)
// Configuration
// ...
return networkManager
}()
// MARK: -
let baseURL: URL
// Initialization
private init(baseURL: URL) {
self.baseURL = baseURL
}
// MARK: - Accessors
class func shared() -> NetworkManager {
return sharedNetworkManager
}
}
Class methods are called directly for reference
NetworkManager.shared()
conclusion
What Is a Singleton and How To Create One In Swift