萌萌の初音
萌萌の初音
发布于 2022-03-21 / 521 阅读
0

kotlin的7种单例模式

接上个文章java的7种单例模式

单例模式的实现:

  • 饿汉模式
object TestDemo {
}
  • 懒汉模式
class TestDemo private constructor() {
    companion object {
        private var instance : TestDemo? = null
        get() {
            if (field == null) field = TestDemo()
            return field
        }
        fun get(): TestDemo {
            return instance!!
        }
    }
}
  • 线程安全的懒汉模式
class TestDemo private constructor() {
    companion object {
        private var instance : TestDemo? = null
        get() {
            if (field == null) field = TestDemo()
            return field
        }
        @Synchronized
        fun get(): TestDemo {
            return instance!!
        }
    }
}
  • 双重校验锁模式
class TestDemo private constructor() {
    companion object {
        val instance : TestDemo by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
            TestDemo()
        }
    }
}

class TestDemo private constructor() {
    companion object {
        @Volatile private var instance : TestDemo? = null
        fun getInstance() {
            instance ?: synchronized(this) {
                instance ?: TestDemo().also { instance = it }
            }
        }
    }
}

延迟属性Lazy:接受一个lambda并返回一个lazy实例的函数,返回的实例可以作为实现延迟属性的委托,第一次调用get()会执行传递给lazy()的lambda表达式并记录结果,后续调用get()只返回记录的结果。

委托属性by:by后边的表达式是委托,get和set会委托给它的setValue和getValue方法。属性的委托不用实现任何接口,但需要提供setValue和getValue方法对应val/var属性。

“?:”操作符:判断左侧非空返回左侧,否则返回右侧。

  • 静态内部类模式
class TestDemo private constructor() {
    companion object {
        val instance = TestBuilder.builder
    }
    
    private object TestBuilder {
        val builder = TestDemo()
    }
}
  • 枚举模式
enum class TestDemo {
    INSTANCE;
    fun test() {}
}
  • AtomicReference原子应用类单例
class TestDemo private constructor() {

    companion object {
        private val INSTANCE = AtomicReference<TestDemo>()
        fun getInstance():TestDemo {
            while (true) {
                var current = INSTANCE.get()
                if (current != null) return current
                current = TestDemo()
                if (INSTANCE.compareAndSet(null, current)) return current
            }
        }
    }

}