According to the Single responsibility principle:
Every class should have responsibility over a single part of the functionality provided by the software
A singleton prevents the creation of multiple instances of a class, providing a global access to it.
But this functionality is not related in any way to the actual functionality of the class and what it should provide.
Does this mean that the Singleton pattern violates the SRP ?
Singleton assure the that each of the thread or class will be using the same consistent object and does not require synchronization. Some argue that they precisely break the single responsibility principle because they control their own creation and lifecycle .
There are two problems with the Singleton pattern: It breaks the Open/Closed Principle, because the singleton class itself is in control over the creation of its instance, while consumers will typically have a hard dependency on its concrete instance.
The most important drawback of the singleton pattern is sacrificing transparency for convenience. Consider the earlier example. Over time, you lose track of the objects that access the user object and, more importantly, the objects that modify its properties.
Singletons hinder unit testing: A Singleton might cause issues for writing testable code if the object and the methods associated with it are so tightly coupled that it becomes impossible to test without writing a fully-functional class dedicated to the Singleton.
Short answer is NO for most cases. Again it can depend on the implementation of the Singleton.
Single Responsibility means that a class should do only one task not the multiple tasks which are not related to each other. Because if the class is performing multiple tasks and any change in requirement, can also break the other functionality of the task. That is why it is always suggest that a class should perform only one task/functionality.
The Singleton is used for restricting only one object creation. This has nothing to do with the class functionality. Usually Singleton is used to avoid creating heavy multiple instance of the class like DB connections. Singleton assure the that each of the thread or class will be using the same consistent object and does not require synchronization.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With