ksnowlv

回顾过去,总结以往;立足现在,铭记当下;技术为主,笔记而已.

Kotlin下的单例

| Comments

单例不同的语言下的要求大体一致。

Kotlin下的单例是通过companion实现的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class KCacheMgr private constructor (){


    companion object {
        @Volatile
        var sharedCacheMgr: KCacheMgr? = null

        fun getInstance(): KCacheMgr {
            if (sharedCacheMgr == null) {
                synchronized(KCacheMgr::class) {
                    if (sharedCacheMgr == null) {
                        sharedCacheMgr = KCacheMgr()
                    }
                }
            }
            return sharedCacheMgr!!
        }
    }
}

Comments

comments powered by Disqus
Included file 'custom/after_footer.html' not found in _includes directory