1双重加锁模式
public class Singleton { private volatile static Singleton singleton; public static Singleton getSingleton(){ if(singleton==null){ synchronized (Singleton.class) { if(singleton==null){ singleton = new Singleton(); } } } return singleton; } private Singleton(){ } }
2静态内部类
public class Singleton { private Singleton(){ } public Singleton getSingleton(){ return SingletonInner.singleton; } private static class SingletonInner{ protected static Singleton singleton = new Singleton(); } }
3枚举
public enum Singleton { Singlton; private Singleton(){ } }
由于java提供了反射机制,第一种和第二种方式通过反射机制仍然有可能生成多个实例