Kotlin专辑

Kotlin 的单例模式的书写方式

2018-03-05  本文已影响81人  梦_之_旅

版权声明:本文为原创文章,未经允许不得转载。

不带参数

第一种

public class SingleCase private constructor() {

    private object Holder { val INSTANCE = SingleCase () }

    companion object {
        val instance: SingleCase by lazy { Holder.INSTANCE }
    }
    var b:String? = null
}

第二种

public class SingleCase private constructor() {
    companion object {
        val instance: = SingleCase ()
    }
    var b:String? = null
}

第三种

public class SingleCase private constructor() {
  companion object {

            /*单例*/
            @Volatile
            private var INSTANCE: SingleCase ? = null

            /*获取单例*/
            val instance: SingleCase 
                get() {
                    if (INSTANCE == null) {
                        synchronized(SingleCase ::class.java) {
                            if (INSTANCE == null) {
                                INSTANCE = SingleCase ()
                            }
                        }
                    }
                    return INSTANCE!!
                }
        }
}

...

带参数

class SingleCase private constructor(str: String) {
    var string: String = str;
    companion object {
        @Volatile
        var instance: SingleCase ? = null

        fun getInstance(c: String): SingleCase {
            if (instance == null) {
                synchronized(SingleCase ::class) {
                    if (instance == null) {
                        instance = SingleCase (c)
                    }
                }
            }
            return instance!!
        }
    }
}

总结

这些也只是我在开发过程中发现和总结的东西,如果谁有更好的方法记得留言或者邮箱(1732685009@qq.com

版权声明:本文为原创文章,未经允许不得转载。

上一篇 下一篇

猜你喜欢

热点阅读