为什么单例会违反开/关原则? [英] 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?
推荐答案
要使一个类开放必须有可能从中继承。继承是是关系。如果您从单例类继承,则子类的实例由于 is-a关系也将成为父类的实例,这意味着您可能突然拥有单例类的多个实例。
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.
这篇关于为什么单例会违反开/关原则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!