Several ways to create singleton singleton pattern

The singleton pattern involves a single class that is responsible for creating its own objects, while ensuring that only a single object is created. This class provides a way to access its unique object, which can be accessed directly without instantiating the object of this class.

That is: ① a single instance can only have one instance; ② a single instance class must create its own unique instance; ③ a single instance class must provide this instance to other objects

1. Lazy mode, thread unsafe

public class Singleton {
    private static Singleton instance;
    private Singleton(){}
    public static Singleton getInstance(){
        if (instance==null){
            instance=new Singleton();
        }
        return instance;
    }
}

2. Lazy mode, thread safety

public class Singleton {
    private static Singleton instance;
    private Singleton(){}
    public static synchronized Singleton getInstance(){
        if (instance==null){
            instance=new Singleton();
        }
        return instance;
    }
}

3. Starved mode, thread safety

public class Singleton {
    private static Singleton instance=new Singleton();
    private Singleton(){}
    public static Singleton getInstance(){
        return instance;
    }
}

4. Double checked locking (DCL)

    private static Singleton instance;
    private Singleton() {}
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                instance = new Singleton();
            }
        }
        return instance;
    }

5. Registration / static internal class

public class Singleton {
    private static class SingletonHolder{
        private static final Singleton instance=new Singleton();
    }
    private Singleton(){}
    public static final Singleton getInstance(){
        return SingletonHolder.instance;
    }
}

6. enumeration

public enum  Singleton {
    INSTANCE;
    public void whateverMethod(){
        
    }
}

 

Posted by elle_girl on Wed, 20 Nov 2019 06:31:50 -0800