Middle
What are the advantages and disadvantages of using the Singleton pattern?
sobes.tech AI
Answer from AI
Advantages:
- Guaranteed single instance of the class.
- Global access point to the instance.
- Lazy loading (on-demand initialization).
Disadvantages:
- Violates the Single Responsibility Principle, as the class is responsible for both creating the instance and its functionality.
- Complicates testing, especially unit testing, as it is difficult to substitute the instance with a mock or stub.
- Can lead to implicit dependencies and complicate refactoring.
- Potential issues with multithreading if thread-safe initialization is not implemented.
- May hide excessive coupling between system components.
Example of thread-safe Singleton implementation in Swift:
final class Singleton {
// Single instance accessible via static property
static let shared = Singleton()
// Private initializer to prevent creation of other instances
private init() {
// Initialization
}
// Example class method
func doSomething() {
print("Singleton is doing something")
}
}