Search code examples
design-patternssingletonsolid-principles

Why singleton breaks open/closed principle?


Could anyone tell me why does singleton break open/closed principle? Is it because there could be problems with inheriting from that class?


Solution

  • For a class to be "open" it must be possible to inherit from it. Inheritance is an "is-a" relationship. If you inherit from a singleton-class then instances of the child-class are also instances of the parent class due to the "is-a" relationship, meaning you can suddenly have multiple instances of the singleton class.

    If the singleton class inhibits inheritance, it's no longer "open".

    If a singleton class allows inheritance, and is "open" for extension, then it can no longer enforce the singleton pattern.