코딩하는 일용직 노동자

코틀린 Singleton Pattern 본문

안드로이드

코틀린 Singleton Pattern

bacass 2020. 6. 8. 14:16

#0 static 
자바의 static처럼 코틀린에서도 인스턴스가 단 하나임을 보장하는 클래스를 만들 수 있습니다.
싱글턴 인스턴스는 전역적으로 사용될 수 있으며, 메모리를 효율적으로 이용할 수 있습니다.

#1 Object
코틀린에서는 클래스 이름앞에 object 키워드를 붙이면 곧바로 싱글톤 클래스가 됩니다.
하지만 이경우에는 생성자를 호출하지 않는 클래스에서만 사용할 수 있습니다.

import android.util.Log

// 싱글톤 클래스를 만들려면 앞에 object 를 붙이면 된다.
object MyObjectSingleton {
    fun printMsg(msg: String) {
        Log.d("MyObjectSingleton", "msg: $msg")
    }
}

 

#2 companion object
생성자를 통해 파라메터를 전달받는 싱글톤 클래스를 만들기 위해선 companion object 를 사용합니다.

import android.content.Context
import android.util.Log

class MySingleton private constructor() {

    // 파라메터를 받는 싱글톤 클래스를 만들려면 companion object를 이용한다.
    companion object {
        private var instance: MySingleton? = null

        private lateinit var context: Context

        fun getInstance(_context: Context): MySingleton {
            return instance ?: synchronized(this) {
                instance ?: MySingleton().also {
                    context = _context
                    instance = it
                }
            }
        }
    }

    fun printMsg(msg: String) {
        Log.d("MySingleton", "msg: $msg")
    }
}

#3 사용하기

private fun testSingleton() {
    // 별도의 객체생성 없이 바로 호출한다.
    MyObjectSingleton.printMsg("Hello World")

    // 객체를 생헝할 수 있다. 하지만 클래스의 메모리 주소값은 동일하다.
    val singleton1 = MySingleton.getInstance(this)
    val singleton2 = MySingleton.getInstance(this)

    Log.d("TEST" , "singleton1: $singleton1")
    Log.d("TEST" , "singleton2: $singleton2")
    singleton1.printMsg("hello world")
    MySingleton.getInstance(this).printMsg("헬로 월드")
}

singleton1 과 singleton2 의 메모리 주소가 같다