6

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 ?

lysergic-acid
  • 17,990
  • 18
  • 96
  • 194

1 Answers1

5

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.

YoungHobbit
  • 12,384
  • 9
  • 44
  • 70
  • 1
    Some argue that they precisely break the single responsibility principle because they control their own creation and lifecycle . Check this out http://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons – Javier Quevedo May 09 '17 at 08:34