java单例模式
1.双重校验锁
public class SSingleton { private static SSingleton INSTANCE; public static SSingleton getInstance() { if (INSTANCE == null) { synchronized (SSingleton.class) { if (INSTANCE == null) INSTANCE = new SSingleton(); } } return INSTANCE; } private SSingleton() { } }
2.枚举
public enum ESingleton { INSTANCE; private ESingleton() { System.out.println("ESingleton"); } public void getI(){ System.out.println("asdf"); } }
3.静态内部类
public class SiSingleton { private static class SingletonHolder { private static final SiSingleton INSTANCE = new SiSingleton(); } private SiSingleton() { } public static final SiSingleton getInstance() { return SingletonHolder.INSTANCE; } }
4.一种新的单例模式
public class RxSingleton { private static final AtomicReference<RxSingleton> INSTANCE = new AtomicReference<RxSingleton>(); private RxSingleton() { } public static RxSingleton getInstance() { for (; ; ) { RxSingleton current = INSTANCE.get(); if (current != null) { return current; } current = new RxSingleton(); if (INSTANCE.compareAndSet(null, current)) { return current; } } } }
5.饿汉
public class EhSingleton { private static EhSingleton instance = new EhSingleton(); private EhSingleton() { } public static EhSingleton getInstance() { return instance; } }
6.懒汉
线程不安全
public class Singleton { private static Singleton instance; private Singleton (){} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
线程安全,效率很低
public class Singleton { private static Singleton instance; private Singleton (){} public static synchronized Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
代码都是乱鸠写的