• 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;  
        }  
    }
  • 相关阅读:
    关于医学的一点想法
    我的ArcGis9.3 到Arcgis10.0 升级步骤
    最近一月的娱乐生活:看电影,玩游戏
    最近一月的娱乐生活:看电影,玩游戏
    5年技术学习历程的回顾
    5年技术学习历程的回顾
    网站开发的技术选型问题
    网站开发的技术选型问题
    学技术真累
    Java实现 LeetCode 200 岛屿数量
  • 原文地址:https://www.cnblogs.com/diaoniwa/p/7299806.html
Copyright © 2020-2023  润新知