1) The static class provides better performance than the Singleton pattern because static methods are bonded on compile time.
2) One more difference between Singleton and static is the ability to override. Since static methods in Java cannot be overridden, they lead to inflexibility. On the other hand, you can override methods defined in Singleton class by extending it.
3) Static classes are hard to mock and consequently hard to test than Singletons, which are pretty easy to mock and thus easy to test. It’s easier to write JUnit test for Singleton than static classes because you can pass mock object whenever Singleton is expected, e.g. into the constructor or as method arguments.
4) If your requirements need to maintain state than Singleton pattern is a better choice than static class, because
maintaining state in later case is a nightmare and leads to subtle bugs.
5) Singleton classes can be lazy-loaded if it is a heavy object, but the static class doesn’t have such advantages and always eagerly loaded.
Example of singleton class in swift
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
import Foundation /// Singleton class with static class class SingletonWithStatic{ public static let shared = SingletonWithStatic() //Manage State fileprivate var counter:Int = 0 private init(){ print("Singleton initialized.") } func callMe() { print("Methods called") self.counter += 1 } func howMenyTimeMethodCalled() { print(counter) } } /// Singleton class without static class class SingletonWithOutStatic { private static var _shared: SingletonWithOutStatic? public static var shared: SingletonWithOutStatic { get{ if _shared == nil { _shared = SingletonWithOutStatic() } return _shared! } } //Manage State fileprivate var counter:Int = 0 private init(){ print("Singleton initialized.") } func callMe() { print("Methods called") self.counter += 1 } func howMenyTimeMethodCalled() { print(counter) } } |
Call singleton object
1 2 3 |
SingletonWithOutStatic.shared.callMe() SingletonWithOutStatic.shared.callMe() SingletonWithOutStatic.shared.howMenyTimeMethodCalled() |