Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Singleton violate the single responsibility principle?

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 ?

like image 225
lysergic-acid Avatar asked Oct 15 '15 18:10

lysergic-acid


People also ask

How does singleton break 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 .

Does the singleton pattern adhere to solid what principle does it follow breach?

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.

Why should we not use singleton pattern?

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.

What is problem with singleton objects?

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.


1 Answers

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.

like image 179
YoungHobbit Avatar answered Jan 02 '23 20:01

YoungHobbit