Kotlin单例模式(带参数和不带参数)

不带参数

public class Singleton private constructor() {
    init { println("This ($this) is a singleton") }    

    private object Holder { private val INSTANCE = Singleton() }

    companion object {
        val instance: Singleton by lazy { Holder.INSTANCE }
    }
    var b:String? = null
}
public class Singleton private constructor() {
    init { println("This ($this) is a singleton") }    

    companion object {
      private  val instance: = Singleton()
    }
    var b:String? = null
}

带参数

class Singleton private constructor(str: String) {
    var string: String = str;

    init {
        println("str is $str")
        println("string is $string")
    }

    companion object {
       @Volatile
        var instance: Singleton? = null

        fun getInstance(c: String): Singleton {
            if (instance == null) {
                synchronized(Singleton::class) {
                    if (instance == null) {
                        instance = Singleton(c)
                    }
                }
            }
            return instance!!
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 注意:所有参数基于JDK7和JDK8提取(java -XX:+PrintFlagsFinal -version),...
    阿飞的博客阅读 17,712评论 3 11
  • 1.不带参数 2.带参数
    Mutoou阅读 3,813评论 0 0
  • 国家电网公司企业标准(Q/GDW)- 面向对象的用电信息数据交换协议 - 报批稿:20170802 前言: 排版 ...
    庭说阅读 13,875评论 6 13
  • 1.迭代器模式概念 迭代器模式(Iterator Pattern),提供一种方法顺序访问一个聚合对象中各个元素, ...
    lgy_gg阅读 2,629评论 0 1
  • 不知道你们是否和我一样 都有一个无法遗忘的她/他 无论过了一个月,还是一年,甚至是一辈子 都还记得他/他 我那个无...
    宸子_chen阅读 1,443评论 0 0