LoginSignup
0
0

More than 3 years have passed since last update.

Kotlinと図で学んでみるデザインパターン -5章 Singletonパターン-

Last updated at Posted at 2019-09-24

Singletonパターン

一度しか生成されないインスタンスを保証する
(今回は図無し)

class Singleton private constructor() {

    init {
        println("インスタンスを作成しました")
    }

    companion object {

        private var instance: Singleton? = null

        fun getInstance(): Singleton = synchronized(this){
            instance ?: Singleton().apply {
                instance = this
            }
        }
    }
}
class TicketMaker private constructor() {
    private var ticket = 1000

    companion object {
        private var instance: TicketMaker? = null

        fun getInstance(): TicketMaker = synchronized(this) {
            instance ?: TicketMaker().apply {
                instance = this
            }
        }
    }

    fun getNextTicketNumber(): Int = synchronized(this) { ticket++ }
}
fun main() {
    println("Start.")

    val obj1 = Singleton.getInstance()
    val obj2 = Singleton.getInstance()

    if (obj1 == obj2) {
        println("obj1とobj2は同じインスタンスです")
    } else {
        println("obj1とobj2は違うインスタンスです")
    }

    println("End.")

    repeat(10) {
        println(TicketMaker.getInstance().getNextTicketNumber())
    }

}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0