Search Your Question

What is singleton class? Pros and Cons.

Ans : The singleton pattern guarantees that only one instance of a class is instantiated. We are aware of following singleton classes,

// Shared URL Session
let sharedURLSession = URLSession.shared

// Default File Manager
let defaultFileManager = FileManager.default

// Standard User Defaults
let standardUserDefaults = UserDefaults.standard

Above classes are instantiate only once, if we try to create another instance, it returns also first instance. So through out application, only one instance is generated for singleton class.

Custom Singleton Class example: 

Different ways : 
1. When we need default configuration  (Using closure) : 

class NetworkManager {

    // MARK: - Properties

    private static var sharedNetworkManager: NetworkManager = {
        let networkManager = NetworkManager(baseURL: API.baseURL)
       // ....
       // Configuration
       // ....         return networkManager
    }()

    let baseURL: URL(string : "https://www.iosiqa.com")

    private init(baseURL: URL) {
        self.baseURL = baseURL
    }

    class func shared() -> NetworkManager {
        return sharedNetworkManager
    }
}

Use  : NetworkManager.shared().baseURL 

2. Using only single statement : 


class mpiosapp {
    
    static var shared = mpiosapp()
    let baseURL: URL(string : "https://www.iosiqa.com")
    private init(){}
    

}

Use : mpiosapp.shared.baseURL

Q : When static variable will be deinitialized?
A : Static variable will be deinit when program or app stops working.

Disadvantage of Singleton :

1. One of the main disadvantages of singletons is that they make unit testing very hard. They introduce global state to the application. The problem is that you cannot completely isolate classes dependent on singletons. When you are trying to test such a class, you inevitably test the Singleton as well. When unit testing, you want the class to be as loosely coupled with other classes as possible and all the dependencies of the class should be ideally provided externally (either by constructor or setters), so they can be easily mocked. Unfortunately, that is not possible with singletons as they introduce tight coupling and the class retrieves the instance on its own. But it gets even worse. The global state of stateful singletons is preserved between test cases.

2. It is static so memory will not be freeze until app will killed. It has it's own creation time and its own lifecycle.

3. Singletons create hidden dependencies. As the Singleton is readily available throughout the code base, it can be overused. Moreover, since its reference is not completely transparent while passing to different methods, it becomes difficult to track. (To solve that we should pass singleton object variable as parameter and this way is called dependency injection).



No comments:

Post a Comment

Thanks