Kotlin 学习之单例模式(java, kotlin)

前言

java 常见的单例模式有三种:

  • 懒汉: getInstance的时候实例化;
  • 饿汉: 引用AA类的时候实例化, 例如 AA.fun() 或者 AA.getInstance();
  • 静态内部类: getInstance的时候实例化, 写法比懒汉要简单;

个人理解: 
如果没有除了getInstance 方法之外的 public static fun 的话, 以上三种单例模式在加载时间上基本是没有差别的. 考虑到实现比较轻松, 推荐静态内部类方式创建单例.


java 静态内部类模式

public class AA {
    private static class Holder{
        private static AA instance = new AA();
    }

    private AA(){}

    public static AA getInstance(){
        return Holder.instance;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

java 懒汉模式

  1. 比较简单的写法是这样:

    public class AA {
        private static AA instance;
        public static AA getInstance(){
            if(instance == null){
                AA = new AA();
            }
            return instance;
        }
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
  2. 但上面这样写不是线程安全的, 如果多线程同时调用 getInstance 时, 有可能同时通过 instance==null 的判断, 导致执行两遍 new AA , 所以需要加锁, 改进写法:

    public class AA {
        private static AA instance;
        public static AA getInstance(){
            if(instance == null){
                synchronized(AA.class){
                    if(instance == null){
                        AA = new AA();
                    }
                }
            }
            return instance;
        }
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
  3. 但这样还是有漏洞, jvm 有指令重排机制, 临界情况下的靠后者有可能会得到一个初始化尚未完成的 instance 对象, 这时需要加 volatile 修饰符, 这个修饰符能组织变量访问前后的指令重排, 改进写法:

    public class AA {
        private volatile static AA instance;
        public static AA getInstance(){
            if(instance == null){
                synchronized(AA.class){
                    if(instance == null){
                        AA = new AA();
                    }
                }
            }
            return instance;
        }
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

kotlin 的单例模式

  • 恶汉 –> 调用AA.getInstance().method()

    class AA private Constructor(){
        fun method(){
            // ...  
        }
        companion object{
            @JvmStatic
            val instance: AA = AA()
        }
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
  • 懒加载 –> 调用AA.getInstance().method()

    class AA private Constructor(){
        fun method(){
            // ...  
        }
        companion object{
            @JvmStatic
            val instance: AA by lazy { AA() }
        }
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
  • 极简单例 (也是懒加载)–> java 中调用 AA.INSTANCE.method(), kotlin 中 AA.method()

    扫描二维码关注公众号,回复: 2648372 查看本文章
    object AA{
        fun method(){
            // ...  
        }
    }
    • 1
    • 2
    • 3
    • 4
    • 5

猜你喜欢

转载自blog.csdn.net/jiankeufo/article/details/80886927