This time I will show you how to define a singleton in Swift and what are the precautions for defining a singleton in Swift. The following is a practical case, let's take a look.
What is a singleton
Single case pattern is the simplest one among design patterns. Even some pattern masters do not call it a pattern, but call it an implementation technique, because the design pattern pays attention to the object. The abstraction of the relationship between objects, while the singleton mode has only one object of its own.
Singleton Pattern, also called monad pattern, is a commonly used software design pattern. When applying this pattern, the class of a singleton object must ensure that only one instance exists. The Singleton design pattern may be the most widely discussed and used design pattern, and it may also be the most frequently asked design pattern in interviews. The main purpose of this design pattern is to ensure that only one instance of a class can appear in the entire system. Of course, this is necessary, such as the global configuration information of your software, or a Factory, or a main control class, etc.How to create a singleton in swift
There are the following two ways to create a singleton in swiftThe way of global variables
let sharedNetworkManager = NetworkManager(baseURL: API.baseURL) class NetworkManager { // MARK: - Properties let baseURL: URL // Initialization init(baseURL: URL) { self.baseURL = baseURL } }
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { print(sharedNetworkManager) return true }
StaticAttributes and privatizationConstruction method
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 } }
NetworkManager.shared()
How to use the on-change attribute in IView
How to use sass configuration in the vue project
The above is the detailed content of Method instances for defining singletons in Swift. For more information, please follow other related articles on the PHP Chinese website!