Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to apply inheritance to a Singleton class?

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.

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,

  • Is this possible?
  • Even if it is possible, what is the use of it?
  • What real world scenario would demand such a use?
like image 551
bragboy Avatar asked May 05 '10 12:05

bragboy


People also ask

What we can do in singleton class to avoid inheritance?

Rules to implement Singleton It should be not be inherited by some other class; i.e., we have to seal the class with sealed key word / we can make constructor private to stop inheritance. Constructor should be Private, to prevent the creation of instance from outside the class.

What is singleton inheritance in Java?

Singleton is characterized by users not calling the constructor but using a static method or service to access the single instance. Making the constructor protected (or private) enforces the pattern, but is not required.

Can we inherit singleton class in C++?

Singleton in C++Inheritance can be supported, but static functions may not be overridden. The base class must be declared a friend of the derived class (in order to access the protected constructor).

Can singleton class be inherited Swift?

A programmer cannot inherit the pure-singleton class. When you try to inherit any class in swift, you must call the constructor of the superclass.


1 Answers

Citing the bible:

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.

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.

like image 62
Michael Borgwardt Avatar answered Oct 18 '22 05:10

Michael Borgwardt