Kotlin 單例模式的幾種寫法

單例 大家很熟悉了 Java里有double check的寫法 還有就是靜態(tài)內(nèi)部類的寫法纵装,在kotlin中有這樣幾種寫法分別為不帶參數(shù) 和帶參數(shù)的寫法 一共4種

參考:?https://medium.com/@BladeCoder/kotlin-singletons-with-argument-194ef06edd9e

一,不帶參數(shù)的單例

object Singleton {

? ? ?init{ //here init your data}

? ? ?fun test(){? }

}??

//搞定 就是這么簡單 使用的時(shí)候?Singleton.INSTANCE.test()? ,?INSTANCE我們沒有定義啊 不要慌張它是自動(dòng)生成的

二,帶參數(shù)的單例? ?A reusable Kotlin implementation?

1评姨,實(shí)現(xiàn)一個(gè)通用的InstanceHolder類?SingletonHolderKt? 可以復(fù)用的實(shí)現(xiàn)方式


2,自己的單例類? ?參考:?https://medium.com/@BladeCoder/kotlin-singletons-with-argument-194ef06edd9e

class Manager?private constructor(context: Context) {

init {

// Init using context argument

}

fun invokeSingletonMethod(){? do something }//我們自己定義的方法

?companion object : SingletonHolder(::Manager) //::Manager這個(gè)直接調(diào)用的是manager的構(gòu)造方法

}

調(diào)用的時(shí)候:Manager.getInstance(your appContext).invokeSingletonMethod();

:: 這個(gè)符號(hào)在kotlin中意思有2個(gè)? 1是 Class References 類引用 2是方法引用?

下邊是stackOverflow上的解釋

Class References: The most basic reflection feature is getting the?runtime reference?to a Kotlin class. To obtain the reference to a statically known Kotlin class, you can use the class literal syntax:

val c = MyClass::class//The reference is a value of type KClass.

Note that a Kotlin class reference is not the same as a Java class reference.?To obtain a Java class reference, use the .java property on a KClass instance.

It’s?also?the syntax for method references as in this simple example:

list.forEach(::println)

It refers to?println?defined in Kotlin Standard library.


kotlin這么實(shí)現(xiàn)的單例 看著代碼并不簡單也不優(yōu)雅 但是 這段代碼是直接從kotlin源碼中l(wèi)azy()方法里摳出來的 下邊是老外的一段解釋

This may not be the most compact or elegant Kotlin code, but it’s the one producing the most efficient bytecode for the double-checked locking algorithm.?Trust the Kotlin authors on this: this code is actually borrowed directly from the implementation of the?lazy()?function in the Kotlin standard library, which is synchronized by default. It has been modified to allow passing an argument to the creator function.

Given its relative complexity, it’s not the kind of code you want to write (or read) more than once, so the goal is to reuse that?SingletonHolder?class everytime you have to implement a singleton with argument.

中心思想就是我們?cè)趧?chuàng)建自己的帶參數(shù)的單例模式時(shí)復(fù)用SingletonHolder 這個(gè)就可以了?

3,還有使用建造者模式實(shí)現(xiàn)的? 下邊是android jetpack架構(gòu)組件中room 數(shù)據(jù)庫單例的實(shí)現(xiàn)方式

You can also use this idiom when a singleton implementation is generated by an external library and the builder requires an argument. Here’s an example using the?Room Persistence Library?for Android:

@Database(entities =arrayOf(User::class), version = 1)

abstract class UsersDatabase : RoomDatabase() {

abstract fun userDao(): UserDao

companion object : SingletonHolder({

Room.databaseBuilder(it.applicationContext,

UsersDatabase::class.java,"Sample.db")

.build()

})

}

如果是沒有參數(shù)的話可以直接使用lazy

Note:?When the builder?doesn’t require an argument, you can simply use a?lazy?delegated property instead:

interface GitHubService {

companion object {

val instance: GitHubServiceby lazy {

val

retrofit = Retrofit.Builder()

.baseUrl("https://api.github.com/")

.build()

retrofit.create(GitHubService::class.java)

}

}

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市腹鹉,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌敷硅,老刑警劉巖功咒,帶你破解...
    沈念sama閱讀 222,378評(píng)論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異绞蹦,居然都是意外死亡力奋,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,970評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門幽七,熙熙樓的掌柜王于貴愁眉苦臉地迎上來景殷,“玉大人,你說我怎么就攤上這事锉走”醭梗” “怎么了藕届?”我有些...
    開封第一講書人閱讀 168,983評(píng)論 0 362
  • 文/不壞的土叔 我叫張陵挪蹭,是天一觀的道長。 經(jīng)常有香客問我休偶,道長梁厉,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,938評(píng)論 1 299
  • 正文 為了忘掉前任踏兜,我火速辦了婚禮词顾,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘碱妆。我一直安慰自己肉盹,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,955評(píng)論 6 398
  • 文/花漫 我一把揭開白布疹尾。 她就那樣靜靜地躺著上忍,像睡著了一般。 火紅的嫁衣襯著肌膚如雪纳本。 梳的紋絲不亂的頭發(fā)上窍蓝,一...
    開封第一講書人閱讀 52,549評(píng)論 1 312
  • 那天,我揣著相機(jī)與錄音繁成,去河邊找鬼吓笙。 笑死,一個(gè)胖子當(dāng)著我的面吹牛巾腕,可吹牛的內(nèi)容都是我干的面睛。 我是一名探鬼主播絮蒿,決...
    沈念sama閱讀 41,063評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢(mèng)啊……” “哼叁鉴!你這毒婦竟也來了歌径?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,991評(píng)論 0 277
  • 序言:老撾萬榮一對(duì)情侶失蹤亲茅,失蹤者是張志新(化名)和其女友劉穎回铛,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體克锣,經(jīng)...
    沈念sama閱讀 46,522評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡茵肃,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,604評(píng)論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了袭祟。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片验残。...
    茶點(diǎn)故事閱讀 40,742評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖巾乳,靈堂內(nèi)的尸體忽然破棺而出您没,到底是詐尸還是另有隱情,我是刑警寧澤胆绊,帶...
    沈念sama閱讀 36,413評(píng)論 5 351
  • 正文 年R本政府宣布氨鹏,位于F島的核電站,受9級(jí)特大地震影響压状,放射性物質(zhì)發(fā)生泄漏仆抵。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,094評(píng)論 3 335
  • 文/蒙蒙 一种冬、第九天 我趴在偏房一處隱蔽的房頂上張望镣丑。 院中可真熱鬧,春花似錦娱两、人聲如沸莺匠。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,572評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽趣竣。三九已至,卻和暖如春纪挎,著一層夾襖步出監(jiān)牢的瞬間期贫,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,671評(píng)論 1 274
  • 我被黑心中介騙來泰國打工异袄, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留通砍,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 49,159評(píng)論 3 378
  • 正文 我出身青樓,卻偏偏與公主長得像封孙,于是被迫代替她去往敵國和親迹冤。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,747評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,346評(píng)論 0 10
  • 山靈水秀虎忌,地靈人杰泡徙,夢(mèng)幻中的天堂。藍(lán)天膜蠢,白云堪藐,小橋,溪水挑围,古鎮(zhèn)礁竞,一直是我想去的地方。 山的魂杉辙,水的情模捂,從小...
    莫言靖毅閱讀 388評(píng)論 0 0
  • # Swift枚舉 枚舉是由用戶定義的數(shù)據(jù)類型的一組相關(guān)值。關(guān)鍵字 `enum` 用來定義枚舉數(shù)據(jù)類型蜘矢。 ###枚...
    刺骨寒閱讀 328評(píng)論 0 0