Does using the Singleton pattern violate the principle of single responsibility?
sobes.tech AI
Answer from AI
Using the Singleton pattern by itself does not necessarily violate the Single Responsibility Principle (SRP). SRP states that a class should have one reason to change, meaning it should be responsible for a single specific task.
A Singleton is a pattern that guarantees a class has only one instance and provides a global point of access to it. If the class implementing the Singleton is responsible for only one responsibility, then SRP is not violated.
However, often Singletons are used for classes that start to perform multiple functions, which leads to a violation of SRP. Therefore, it is important to separate responsibilities and not overload the Singleton with unnecessary duties.
An example of a correct Singleton:
class Logger {
static let shared = Logger()
private init() {}
func log(_ message: String) {
print(message)
}
}
Here, Logger is responsible only for logging, and the Singleton is used for convenient access to the single instance.