饱汉模式
public class Singleton { private static Singleton instance = new Singleton(); private Singleton() {} public static Singleton getInstance() { return instance; } }
饥汉模式
public class Singleton { private static Singleton instance = null; private Singleton() {} public synchronized static Singleton getInstance() { if(instance == null) instance = new Singleton(); return instance; } }
枚举
public enum Singleton { INSTANCE(); private Singleton() {} public void method() { // do something } }
public class Multiton { private static Multiton instance1 = new Multiton(); private static Multiton instance2 = new Multiton(); private Multiton() {} public static Multiton getInstance(int key) { if(key == 1) { return instance1; } else { return instance2; } } }
原文:http://www.cnblogs.com/wangj1130/p/4843150.html