只需要单个实例:
比如factory
/** * 饿汉式 * 类加载到内存中后,就实例化一个单例,JVM保证线程安全: * 因为JVM加载类 保证只会加载一次 */ public class Single01 { private static final Single01 INSTANCE = new Single01(); private Single01() { } public static Single01 getInstance(){ return INSTANCE; } }
/** * 把实例化 写入静态代码块 */ public class Single02 { private static final Single02 INSTANCE; static { INSTANCE = new Single02(); } private Single02() { } public static Single02 getInstance() { return INSTANCE; } }
/** * 懒汉式 * 不调用则不会实例化对象 * 但其实有线程安全问题 大并发下不推荐 */ public class Single03 { private static Single03 INSTANCE; private Single03(){ } public Single03 getInstance(){ if(INSTANCE == null){ INSTANCE = new Single03(); } return INSTANCE; } }
/** * 检查两次的方式解决了03中的线程安全问题 */ public class Single04 { public static Single04 INSTANCE; private Single04(){ } public Single04 getINSTANCE(){ if(INSTANCE == null){ synchronized (Single04.class){ if(INSTANCE == null){ INSTANCE = new Single04(); } } } return INSTANCE; } }
/** * 静态内部类方式 * 因为JVM加载外部类时不会加载内部类 */ public class Single05 { private Single05(){ } private static class Single05Holder{ private static final Single05 INSTANCE = new Single05(); } public Single05 getINSTANCE(){ return Single05Holder.INSTANCE; } }
《effective java》 中给出枚举单例的写法:
/** * 枚举单例 * 利用枚举类的单例实现 */ public enum Single06 { INSTANCE; }