一、不注重性能的情况
package singleton;public class SlowSingleton { PRivate static SlowSingleton instance; private SlowSingleton() { }; public static synchronized SlowSingleton getInstance() { if (instance == null) { instance = new SlowSingleton(); } return instance; }}二、注重性能,急切创建实例的方案package singleton;public class FastSingleton { private static FastSingleton instance = new FastSingleton(); private FastSingleton() { }; public static FastSingleton getInstance() { return instance; }}这种方法的缺点是:不能延迟实例化
三、注重性能,double check 方案
package singleton;public class DoubleCheckSingleton { private volatile static DoubleCheckSingleton instance; private DoubleCheckSingleton() { }; public static DoubleCheckSingleton getInstance() { if (instance == null) { synchronized (DoubleCheckSingleton.class) { if (instance == null) { instance = new DoubleCheckSingleton(); } } } return instance; }}四、注重性能,静态内部类方案package singleton;public class MagicSingleton { private static class SingletonHolder { private static final MagicSingleton INSTANCE = new MagicSingleton(); } private MagicSingleton() { } public static final MagicSingleton getInstance() { return SingletonHolder.INSTANCE; }}五、注重性能,枚举类方案package singleton;public enum EnumSingleton { INSTACE; public static EnumSingleton getInstance() { return INSTACE; } public void someMethod(){ System.out.println("ooo"); } // 使用方法 public static void main(String[] args) { EnumSingleton.INSTACE.someMethod(); // 或者 EnumSingleton.getInstance().someMethod(); }}
新闻热点
疑难解答