3 Useful Singleton Pattern in Java

1. Eager initialization (thread-safe)

 

/**
* Singleton pattern example with eager initialization way.
* @author <a href="mailto:[email protected]">futeng</a>
*/
public class EagerInitSingletion {

    private static final EagerInitSingletion INSTANCE = new EagerInitSingletion();

    private EagerInitSingletion() {}

    public static EagerInitSingletion getInstance() {
        return INSTANCE;
    }
}

 

2. Double-checked locking (lazy initialization, thread-safe)

/**
* Singleton pattern example with double-checked locking
* @author <a href="mailto:[email protected]">futeng</a>
*/
public class DoubleCheckedSingleton {

    private static volatile DoubleCheckedSingleton INSTANCE = null;

    private DoubleCheckedSingleton() {};

    // Double-checked locking
    public static DoubleCheckedSingleton getInstance() {
        if(INSTANCE == null) {
            synchronized (DoubleCheckedSingleton.class) {
                if(INSTANCE == null) {
                    INSTANCE = new DoubleCheckedSingleton();
                }
            }
        }
        return INSTANCE;
    }
}
 

 

3. Enum way (lazy initialization, thread-safe)

What is the best way to implements a Singleton pattern in Java? Enum way

 

simplest 

public enum EnumWaySingleton {
       INSTANCE;
   }

 more complex

/**
* Singleton Pattern using Java ENUM
* @author <a href="mailto:[email protected]">futeng</a>
*/
public enum EnumWaySingleton {
    INSTANCE;

    private final String[] names = {"xiaoqi", "xiaodi"};

    public void printNames() {
        System.out.println(Arrays.toString(names));
    }

    public static void main(String[] args) {
        EnumWaySingleton.INSTANCE.printNames();
    }
}

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(java,设计模式,Singleton,designpattern)