Dealing with Singletons which have to subclass

后端 未结 3 690
栀梦
栀梦 2021-02-14 07:26

In the question What is an efficient way to implement a singleton pattern in Java? the answer with the most upvotes says, to use a Enum for implementing a singleton.

Tha

相关标签:
3条回答
  • 2021-02-14 07:58

    A Singleton class can extend other classes; actually by default in Java it would anyway extend Object. However what Josh is referring to is that you shouldn't extend a Singleton class because once you extend it, there is more than 1 instance present.

    Answering the comment:

    Actually the best way to implement the Singleton is:

    From Effective Java

    // Singleton with static factory
    public class Elvis {
    private static final Elvis INSTANCE = new Elvis();
    private Elvis() { ... }
    public static Elvis getInstance() { return INSTANCE; }
    public void leaveTheBuilding() { ... }
    }
    

    Here Elvis can extend any other class.

    0 讨论(0)
  • 2021-02-14 08:01

    Josh is referring to extending the enum type, not to having the singleton type extend something else.

    0 讨论(0)
  • 2021-02-14 08:03

    You shouldn't care about the actual instance(s) of your servlets - lifecycle management is handled by the servlet container according to the Servlet specification contract to which you have agreed. If it makes sense to implement parts of you server-side functionality as a singleton, then go ahead and do that any way you like and use it from your servlet.

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