- 方式一(不含参)
class Single private constructor() { init {//初始化 } private object Holder { val INSTANCE = Single() } companion object { val instance: Single by lazy { Holder.INSTANCE } }}复制代码
- 方式二(带参数)
class Singleton private constructor(str: String) { init { println("Init") } companion object { @Volatile var instance: Singleton? = null fun getInstance(a: String) { if (instance == null) { synchronized(Singleton::class) { if (instance == null) { instance = Singleton(a) } } return instance!! } } }}复制代码
测试实现
fun main(args: Array) { Single.instance Singleton.getInstance("a")}复制代码