单身继承 [英] Singleton Inheritance

查看:162
本文介绍了单身继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从单例类继承为需要相同功能的其他类?
这样的东西有什么意义吗?

How do I inherit from a singleton class into other classes that need the same functionality? Would something like this make any sense?

推荐答案

Jon Skeet 一段时间写了这个。虽然使用嵌套的内部类确实有一些希望,但是可以使用Singleton来实现继承的一些的优点。它没有无限的可扩展性,它只是让Singleton在运行时选择自己的实现的一种技术。

Jon Skeet wrote about this a while back. It is possible to achieve some of the benefits of inheritance with the Singleton, although using nested inner classes does leave a little to be desired. It doesn't have infinite extensibility, it's only a technique for having a Singleton choose its own implementation at runtime.

实际上,继承自Singleton并不能做到这一点很有意义,因为Singleton模式的一部分是实例管理,一旦你已经有一个基本类型的物理实例,那么在派生类型中覆盖任何这些实例是太晚了。即使可以,我怀疑它可能导致难以理解的设计,甚至更难测试/维护。

Realistically, inheriting from a Singleton doesn't make all that much sense, because part of the Singleton pattern is instance management, and once you already have a physical instance of a base type then it's too late to override any of this in the derived type. Even if you could, I suspect that it could lead to a design that's difficult to understand and even more difficult to test/maintain.

这篇关于单身继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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