为什么单例会破坏open/closed原则?
Why singleton breaks open/closed principle?
谁能告诉我为什么单例会破坏open/closed原则?
是因为从 class 继承可能有问题吗?
要使 class 成为 "open",必须可以继承它。继承是一种 "is-a" 关系。如果您继承自单例-class,那么由于 "is-a" 关系,子 class 的实例也是父 class 的实例,这意味着您可以突然拥有多个单例实例 class.
如果单例class禁止继承,则不再是"open"。
如果一个单例class允许继承,并且"open"用于扩展,那么它就不能再强制执行单例模式了。
单例模式有两个问题:
- 它打破了 Open/Closed 原则,因为单例 class 本身控制着它的实例的创建,而消费者通常会强烈依赖它的具体实例。这不允许更改实现,而不必对整个应用程序进行全面更改。
- 它打破了依赖倒置原则 (DIP),因为消费者总是直接依赖具体的 class 来获取实例,而 DIP 规定了抽象的使用。这会导致 Singleton 实现被拖延,并且不允许通过将实现包装在装饰器中或在没有该 singleton 实现的情况下分发客户端来添加横切关注点。
单例设计模式禁止继承是一种常见的误解。那根本不是真的。
来自 GoF 书,第 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.
...然后在第 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.
第 130 页详细介绍了有关配置 Singleton 子类的信息。
Singleton 破坏 OCP 的原因是它没有,至少不是天生的。它恰好最常被未读过 GoF 书的开发人员违反 OCP 实现。工厂方法模式也遭遇同样的命运。
谁能告诉我为什么单例会破坏open/closed原则? 是因为从 class 继承可能有问题吗?
要使 class 成为 "open",必须可以继承它。继承是一种 "is-a" 关系。如果您继承自单例-class,那么由于 "is-a" 关系,子 class 的实例也是父 class 的实例,这意味着您可以突然拥有多个单例实例 class.
如果单例class禁止继承,则不再是"open"。
如果一个单例class允许继承,并且"open"用于扩展,那么它就不能再强制执行单例模式了。
单例模式有两个问题:
- 它打破了 Open/Closed 原则,因为单例 class 本身控制着它的实例的创建,而消费者通常会强烈依赖它的具体实例。这不允许更改实现,而不必对整个应用程序进行全面更改。
- 它打破了依赖倒置原则 (DIP),因为消费者总是直接依赖具体的 class 来获取实例,而 DIP 规定了抽象的使用。这会导致 Singleton 实现被拖延,并且不允许通过将实现包装在装饰器中或在没有该 singleton 实现的情况下分发客户端来添加横切关注点。
单例设计模式禁止继承是一种常见的误解。那根本不是真的。
来自 GoF 书,第 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.
...然后在第 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.
第 130 页详细介绍了有关配置 Singleton 子类的信息。
Singleton 破坏 OCP 的原因是它没有,至少不是天生的。它恰好最常被未读过 GoF 书的开发人员违反 OCP 实现。工厂方法模式也遭遇同样的命运。