单例设计模式用于派生类 [英] Singleton Design pattern for derived classes

查看:329
本文介绍了单例设计模式用于派生类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以生成单例  design pattren ,它可用于为基类的所有派生类返回单例实例。

I was wondering if it is possible to produce singleton design pattren in place which can be used to return singleton instance for all the derived classes of a base class.

例如,如果Parent是我的基类,child1和child 2是其子类。我想要一些mecahnism,当我调用Parent.GetInstance()方法时,此方法应该确保返回child1和child2的singleton对象。

For example if Parent is my base class and child1 and child 2 are its child classes. I want some mecahnism by which when i call Parent.GetInstance() method, this method should ensure to return singleton object for child1 and child2.

任何指针都将被赞赏。

 

推荐答案

单身设计模式非常邪恶。单例很难测试,它们在整个应用程序中创建(和分散)依赖关系(依赖于单例)。单例的变化可能会导致问题在整个代码库中以
级联;我会保持清醒。

Hi, the singleton design pattern is pretty much evil. Singletons are difficult* to test and they create (and scatter) dependencies all over the application (dependencies to the singleton). A change in the singleton could cause problems to cascade through the whole code base; I'd stay well clear.

 

*实际上它们很容易测试,但依赖性问题再次发挥作用。所有使用单例的测试都相互依赖。

*Actually they are easy to test but the dependency issue plays it's part again. All tests that use the singleton become dependent on each other.


这篇关于单例设计模式用于派生类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆