「Android/kotlin/singleton」の版間の差分
提供: 初心者エンジニアの簡易メモ
(ページの作成:「==singletonサンプル== MainActivity.kt HogeSingleton.setName("hogehoge") Log.i("test", "HogeSingleton.getName()=" + HogeSingleton.getName()) // hogehoge HogeSinglet...」) |
|||
| 行1: | 行1: | ||
==singletonサンプル== | ==singletonサンプル== | ||
| + | ===companion objectを使うパターン=== | ||
MainActivity.kt | MainActivity.kt | ||
| − | + | <pre> | |
| − | + | HogeSingleton.setName("hogehoge") | |
| + | Log.i("test", "HogeSingleton.getName()=" + HogeSingleton.getName()) // hogehoge | ||
| + | </pre> | ||
HogeSingleton.kt | HogeSingleton.kt | ||
| 行8: | 行11: | ||
class HogeSingleton { | class HogeSingleton { | ||
companion object { | companion object { | ||
| + | private var name = "" | ||
| + | fun setName(name: String) { | ||
| + | this.name = name | ||
| + | } | ||
| + | fun getName(): String { | ||
| + | return this.name | ||
| + | } | ||
| + | } | ||
| + | } | ||
| + | </pre> | ||
| + | |||
| + | ===Classを使うパターン=== | ||
| + | 仮にclass名をInstanceとした。 | ||
| + | |||
| + | MainActivity.kt | ||
| + | <pre> | ||
| + | HogeSingleton.Instance.setName("hogehoge") | ||
| + | Log.i("test", "HogeSingleton.getName()=" + HogeSingleton.Instance.getName()) // hogehoge | ||
| + | </pre> | ||
| + | HogeSingleton.kt | ||
| + | <pre> | ||
| + | class HogeSingleton { | ||
| + | object Instance { | ||
private var name = "" | private var name = "" | ||
fun setName(name: String) { | fun setName(name: String) { | ||
2020年2月14日 (金) 13:50時点における最新版
singletonサンプル
companion objectを使うパターン
MainActivity.kt
HogeSingleton.setName("hogehoge")
Log.i("test", "HogeSingleton.getName()=" + HogeSingleton.getName()) // hogehoge
HogeSingleton.kt
class HogeSingleton {
companion object {
private var name = ""
fun setName(name: String) {
this.name = name
}
fun getName(): String {
return this.name
}
}
}
Classを使うパターン
仮にclass名をInstanceとした。
MainActivity.kt
HogeSingleton.Instance.setName("hogehoge")
Log.i("test", "HogeSingleton.getName()=" + HogeSingleton.Instance.getName()) // hogehoge
HogeSingleton.kt
class HogeSingleton {
object Instance {
private var name = ""
fun setName(name: String) {
this.name = name
}
fun getName(): String {
return this.name
}
}
}
