Kotlin實現常用的五種單例模式
阿新 • • 發佈:2018-11-19
廢話不多說,直接上程式碼,記錄一下,方便以後使用
class ImageClassifyUtil private constructor(){ /** * 餓漢 */ companion object { val instance = ImageClassifyUtil() } /** * 懶漢 */ companion object { private var instance: ImageClassifyUtil? = null get() { if (field == null) { field = ImageClassifyUtil() } return field } fun get(): ImageClassifyUtil { return instance!! } } /** * 執行緒安全的懶漢 */ companion object { private var instance: ImageClassifyUtil? = null get() { if (field == null) { field = ImageClassifyUtil() } return field } @Synchronized fun get(): ImageClassifyUtil { return instance!! } } /** * 雙重校驗 */ companion object { val instance: ImageClassifyUtil by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { ImageClassifyUtil() } } /** * 靜態內部類 */ companion object { val instance = ImageClassifyHolder.holder } private object ImageClassifyHolder { val holder = ImageClassifyUtil() } }
ps:歷史給人的唯一教訓,就是人們從未在歷史中吸取過任何教訓
ps:秦人不暇自哀,而後人哀之;後人哀之而不鑑之,亦使後人而復哀後人也”基本同義。