是否可以将继承应用于Singleton类? [英] Is it possible to apply inheritance to a Singleton class?

查看:126
本文介绍了是否可以将继承应用于Singleton类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我在采访中遇到了一个问题。是否可以在Singleton类上应用继承概念?我说过,由于构造函数是私有的,所以我们不能扩展该Singleton类。

Today I faced one question in interview. Is it possible to apply inheritance concept on Singleton Classes? I said since the constructor is private, we cannot extend that Singleton class.

他接下来要问我的是在该Singleton类上应用继承。因此,我将Singleton的构造函数作为受保护的对象,认为孩子的构造函数也已受到保护。但是我错了,孩子可以有一个等于或大于该值的修饰语。

Next thing he asked me is to apply inheritance on that Singleton class. So, I made the Singleton's constructor as protected thinking that child's constructor also has be protected. But I was wrong the child can have a modifier either equal to or higher than that.

因此,我请他举一个关于这种情况的真实例子。他不能给我一个,说我不能问问题,要我告诉我这种情况是否可能。

So, I asked him to give a real world example on such a case. He was not able to give me one and said that I cant ask questions and wanted me to tell whether this scenario is possible or not.

我有点空白。我的问题是,

I went kind of blank. My question here is,


  • 这可能吗?

  • 即使有可能,那是什么

  • 什么样的现实世界场景会要求这样使用?

推荐答案

引用圣经


当单个实例应通过子类扩展为
且客户应为
可以使用扩展实例
而无需修改其代码。

Use the Singleton pattern when [...] the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code.

Singleton模式具有
的一些好处:[...]
3.允许改进操作和表示。 Singleton
类可能是子类,并且使用此扩展类的实例
配置应用程序很容易。
您可以在
运行时为应用程序配置
所需的类实例。

The Singleton pattern has several benefits: [...] 3. 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.

关于如何实现这一点:这本书提出了几种方法,其中最复杂的是通过名称查找实例的注册表。

As for how to implement this: the book suggests several way, the most sophisticated of which is a registry in which instances are looked up by name.

这篇关于是否可以将继承应用于Singleton类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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