Is it possible to apply inheritance to a Singleton class?

前端 未结 8 2068
孤独总比滥情好
孤独总比滥情好 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: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.

提交回复
热议问题