?
class="java">/** * Singleton pattern example with eager initialization way. * @author <a href="mailto:ifuteng@gmail.com">futeng</a> */ public class EagerInitSingletion { private static final EagerInitSingletion INSTANCE = new EagerInitSingletion(); private EagerInitSingletion() {} public static EagerInitSingletion getInstance() { return INSTANCE; } }
?
/** * Singleton pattern example with double-checked locking * @author <a href="mailto:ifuteng@gmail.com">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; } }
?
?
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:ifuteng@gmail.com">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(); } }
?
?
?
?
?
?
?
?
?
?
?