public class Singleton { private static Singleton instance = new Singleton(); private Singleton() { } public static Singleton getInstance() { retun instance; } }
public class Singleton { private static Singleton instance = null; private Singleton() { } public static Singleton getInstance () { if (instance == null) { instatnce = new Singleton(); } return instance; } }
public class Singleton { private static Singleton instance = null; private Singleton() { } public static synchronized Singleton getInstance () { if (instance == null) { instatnce = new Singleton(); } return instance; } }
public class Singleton { private static Singleton instance = null; private Singleton () { } public static Singleton getInstance () { // If already initialized, no need to get lock everytime. if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance ; } }
public class Singleton() { private Singleton() { } public static Singleton getInstance () { return SingletonHolder.instance; } /** * 靜態內部類,只有在裝載該內部類時纔會去建立單例對象 */ private static class SingletonHolder { private static final Singleton instance = new Singleton(); } }
public enum Singleton { // 定義一個枚舉的元素,它就是Singleton的一個實例 INSTANCE; public void doSomethig() { // TODO: } }
Singleton singleton = Singleton.INSTANCE; singleton.doSomething();
public class SingletonManager { private static Map<String, Object> objMap = new HashMap<>(); private Singleton() { } public static void addSingleton(String key, Object instance) { if (!objMap.containsKey(key)) { objMap.put(key, instance); } } public static getSingleton(String key) { return objMap.get(key); } }