How can I implement an abstract singleton class in Java?

前端 未结 6 458
日久生厌
日久生厌 2020-12-15 16:48

Here is my sample abstract singleton class:

public abstract class A {
    protected static A instance;
    public static A getInstance() {
        return ins         


        
6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-15 17:33

    In addition to problems others have pointed out, having the instance field in A means that you can only have one singleton in the entire VM. If you also have:

    public class C extends A {
        private C() { }
        static {
            instance = new C();
        }
        //...implementations of my abstract methods...
    }
    

    ... then whichever of B or C gets loaded last will win, and the other's singleton instance will be lost.

    This is just a bad way to do things.

提交回复
热议问题