Java设计模式Kotlin开发知识禅与计算机程序设计艺术

Kotlin & Java 之单利模式

2018-03-31  本文已影响110人  温暖的外星
    在 Java 中单例模式的写法存在N种写法,这里只列举其中的几种。
    class UserProFile {

        private static UserProFile Instance = null;

        public UserProFile() {
        }

        public static UserProFile getInstance() {
            if (Instance == null) {
                Instance = new UserProFile();
            }
            return Instance;
        }
    }
    class UserProFile {

        private static UserProFile Instance = new UserProFile();

        public UserProFile() {
        }

        public static UserProFile getInstance() {
            return Instance;
        }
    }
    class UserProFile {

        private static UserProFile Instance = null;

        public UserProFile() {
        }

        public static UserProFile getInstance() {
            if (Instance == null) {
                synchronized (UserProFile.class) {
                    if (Instance == null) {
                        Instance = new UserProFile();
                    }
                }
            }
            return Instance;
        }
    }
    class UserProFile {

        private volatile static UserProFile Instance;

        public static UserProFile getInstance() {
            UserProFile inst = Instance;
            if (inst == null) {
                synchronized (UserProFile.class) {
                    inst = Instance;
                    if (inst == null) {
                        inst = new UserProFile();
                        Instance = inst;
                    }
                }
            }
            return inst;
        }
    }


---

- 这里讨论下 DoubleCheck 单利的写法

关于 DoubleCheck 这种单利写法, 在实际开发中是能够保护线程安全的, 比如第三种单例写法进行了双重判断, 在线程A进行访问的时候,线程B也请求过来了,这时就会出现对象错乱的情况,
那么在第四种单例模式中添加了 volatile 关键字之后, 就不会出现类似问题了, 因为 volatile 关键字可以保证对象在实例化以及对象的调用是有序的, 比如在线程A中在实例的时候线程B看到的实例
赋值以及构造方法其实是有序的调用, 先调用构造方法实例化完成之后才给 inst 赋值, 那也就是说 如果 inst 为 Null 一定是没有初始化完成, 如果 inst 不为 Null 那么一定初始化完成。


---
        class UserProFile {

            companion object {

                val instances by lazy(mode =  LazyThreadSafetyMode.SYNCHRONIZED){
                    UserProFile()
                }

                private @Volatile var mInstance : UserProFile? = null

                fun getInstance(): UserProFile {

                    if (null == mInstance){

                        synchronized(this){
                            if (null == mInstance){
                                mInstance = UserProFile()
                            }
                        }
                    }
                    return mInstance!!
                }
            }

        }
       SYNCHRONIZED

       PUBLICATION

       NONE
上一篇 下一篇

猜你喜欢

热点阅读