Is it possible to apply inheritance to a Singleton class?

前端 未结 8 1976
孤独总比滥情好
孤独总比滥情好 2021-01-30 23:05

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 Singlet

相关标签:
8条回答
  • 2021-01-30 23:46

    I'm guessing this isn't what he wasn't looking for, but if you want to get technical you could also mention that Singleton is a pattern, not an implementation. Messing with the class constructor isn't the only way to have a Singleton, you could have a factory enforcing the pattern, in which case you can use inheritance in exactly the same way as with other classes.

    0 讨论(0)
  • 2021-01-30 23:53

    You can create an abstract base class with a bunch of common attributes and methods, and then create a number of subclasses as singleton classes. That is "applying the inheritance concept" ... in a useful way.

    But what you cannot do is create a subclass of a strictly implemented singleton class. If you declare the singleton classes constructor as private a subclass won't compile. If you declare it with some other access, the constructor could be used in another class to create multiple instances ... ergo it is not strictly a singleton. If you declare the singleton as abstract, it cannot be instantiated at all ... ergo it is not a singleton.

    0 讨论(0)
提交回复
热议问题