kotlin学习小记--单例

来源:互联网 发布:苏联歌曲 知乎 编辑:程序博客网 时间:2024/05/23 13:03

1.懒人写法

最简单的写法,直接用object声明

 object Singleton{}

对应java中的饿汉模式写法

 public class Singleton {    public static final Singleton instance = new Singleton();    public Singleton getInstance() {        return instance;    }}

这种方式在类加载的时候就创建实例,虽然占不了多少时间,总归会拖慢类加载速度。

2.基本懒加载

class Singleton private constructor{    companion object {        val intance by lazy(LazyThreadSafetyMode.NONE) { Singleton() }    }}

对应java中的懒汉式写法

public class Singleton {    public static Singleton instance = null;    private Singleton (){}    public Singleton getInstance() {        if (instance == null) {            instance = new Singleton();        }        return instance;    }}

这种方法实现了懒加载,但是它不是线程安全的,可能在多个线程中创建多个不同的实例。

3.线程同步单例一

class Singleton private constructor(){    companion object {        lateinit var instance: Singleton        @Synchronized        fun get(): Singleton {            if (instance == null) {                instance = Singleton();            }            return instance!!        }    }}

对应java中

public class Singleton {    private static Singleton instance = null;    private Singleton (){}    public static synchronized  Singleton getInstance() {        if (instance == null) {            instance = new Singleton();        }        return instance;    }}

其实kotlin这种写法可以说是java直译过来的,有点卖萌的嫌疑,这边只是在写法上做个比较,虽说是线程安全的,但是太影响效率。主要看下面这种

4.线程同步单例二

class Singleton private constructor(){    companion object {        val intance by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { Singleton() }    }}

对应java中双检锁单例

public class Singleton {    private static  Singleton instance = null;    private Singleton (){}    public static Singleton getInstance() {        if (instance == null) {            synchronized (Singleton.class) {                if (instance == null) {                    instance = new Singleton();                }            }        }        return instance;    }}

线程同步,懒加载,无同步引起的效率问题。(java代码真心难看)

5.静态内部类单例

java中我最长用到的一种单例方式,简洁、优雅、无痛

public class Singleton {    private Singleton (){}    private static class Holder {        private static Singleton instance = new Singleton();    }    public static Singleton getInstance(){        return Holder.instance;    }}

kotlin 中也差不多是java直译了吧

class Singleton private constructor(){    companion object {        fun getInstance(): Singleton {            return Holder.instance        }    }    private object Holder {        val instance = Singleton()    }}
原创粉丝点击