Is it possible to apply inheritance to a Singleton class?

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

    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.

提交回复
热议问题