Android
[안드로이드 / Kotlin ] Singleton Pattern
amid.jungs
2022. 3. 8. 11:51
Ⅰ. 개념
싱글톤 패턴 : 객체의 인스턴스 1개를 생성하여 재사용하는 패턴
Ⅱ. 특징
• 애플리케이션 시작 ~ 종료까지 한 번 생성으로 고정된 메모리 영역을 가져 메모리를 효율적으로 사용 가능
• 전역 인스턴스이므로 다른 클래스의 인스턴스가 데이터를 공유 및 변경이 가능함
• 객체를 여러개 생성해서 사용할 때 사용
Ⅲ. 예제
• object 키워드 사용
object SingletonEx {
fun printName (name : String) {
Log.d("singleton log" , "name : $name")
}
• companion object 사용
class SingletonEx() private constructor() {
companion object {
private var instance: SingletomEx? = null
private lateinit var context : Context
fun getInstance(_context : Context) : SingletonEx {
return instance ?: synchronized(this) {
instance ?: SingletonEx().also {
context = _context
instance = it
}
}
}
}
fun printName (name : String) {
Log.d("SingletonEx" , "sing : $sing")
}
}
• 사용
private fin textSingleton() {
SingletonEx.printName("Hi")
val singleton1 = SingletonEx.getInstance(this)
val singleton2 = SingletonEx.getInstance(this)
singletonEx1.printName("Hi")
SingletonEx.getInstance(this).printName("안녕")
}