Could anyone tell me why does singleton break open/closed principle? Is it because there could be problems with inheriting from that class?
Another point to note here is that the Singleton design pattern violates the Single Responsibility Principle since the objects control how they are created and manage their life-cycle. This clearly contradicts the Single Responsibility Principle which states that a class should have one and only one reason for change.
There are many ways to prevent Singleton pattern from Reflection API, but one of the best solutions is to throw a run-time exception in the constructor if the instance already exists. In this, we can not able to create a second instance.
Serialization is used to convert an object of byte stream and save in a file or send over a network. Suppose you serialize an object of a singleton class. Then if you de-serialize that object it will create a new instance and hence break the 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.
It is a common misconception that the Singleton design pattern prohibits inheritance. That is simply not true.
From the GoF book, page 127:
Use the Singleton pattern when
- there must be exactly one instance of a class, and it must be accessible to clients from a well-known access point.
- when the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code.
...and again on page 128:
The Singleton pattern has several benefits:
- Permits refinement of operations and representation. The Singleton class may be subclassed, and it's easy to configure an application with an instance of this extended class. You can configure the application with an instance of the class you need at run-time.
Page 130 goes into detail about configuring Singleton subclasses.
The answer to why Singleton breaks the OCP is that it doesn't, at least not inherently. It just happens to be most commonly implemented in violation of the OCP by developers who have not read the GoF book. The Factory Method pattern suffers much the same fate.
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