我们应该封单身?我们应尝试从单身摆在首位继承? [英] Should we seal Singletons? Should we try to inherit from Singletons in the first place?

查看:147
本文介绍了我们应该封单身?我们应尝试从单身摆在首位继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果一个Singleton类被允许有孩子吗?我们是否应该封呢?什么是亲的和反对的?



有关能够从一个Singleton类继承,我们将不得不作出保护,而不是私人的构造函数。现在,这将是在C#罚款,但在Java中保护字提供两个子类和包装类访问构造函数。这不仅意味着我们的辛格尔顿继承可以访问在同一个包中的构造函数,但其​​他类可以做到这一点的类。



我有点困惑这一切事实。也许我作出有关完全不用担心太上大做文章?到现在为止,我从来没有试图从一个Singleton继承任何必要性,所以也许这只是一个学术问题!



感谢


< DIV CLASS =h2_lin>解决方案

是的,单身应密封保存。不,他们不应该被继承。



的原因是主要的(真正的只有的)一个Singleton的行为是创建的一个实例本身在一些预定的时间。因为该功能是静态的,它不能被重写,所以它必须被代替复制。一旦你开始复制,你有一个单身,这并没有真正意义的多个实例。



如果不是这样,你最终的比赛条件或其他冲突的派生出来的单身在全局实例,这不仅没有任何意义的控制而战,这是危险的。



有一些hackish的解决方法的辛格尔顿继承问题,但就是它们是什么 - 黑客。 Singleton模式是不是真的适合继承。


Should a Singleton class be allowed to have children? Should we seal it? What are the pro's and con's?

For being able to inherit from a Singleton class, we would have to make the constructor protected instead of private. Now, that will be fine in c#, but the protected word in java gives both child-classes and package-classes access to the constructor. Which means not only classes that inherit from our Singleton can access the constructor but other classes in the same package can do it.

I'm a bit confused about all this facts. Maybe I am making a big fuss about nothing to worry about too much? Until now, I never had any necessity of trying to inherit from a Singleton, so maybe this is just an academic question!

Thanks

解决方案

Yes, Singletons should be sealed. No, they should not be inherited.

The reason is that the primary (really only) behaviour of a Singleton is to create an instance of itself at some predetermined time. Since this functionality is static, it can't be overridden, so it would have to be duplicated instead. Once you start duplicating, you have multiple instances of a singleton, which doesn't really make sense.

Either that or you end up with race conditions or other conflicts as the "derived" singletons fight for control over the global instance, which not only doesn't make sense, it's dangerous.

There are some hackish workarounds to the Singleton inheritance problem, but that is what they are - hacks. The Singleton pattern is not really suitable for inheritance.

这篇关于我们应该封单身?我们应尝试从单身摆在首位继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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