저번에 못다한 과제 수정 오늘에서야 한다 ㅠㅠ
singleton 구현방식 비교해보기
DetailActivity, MainActivity
먼저 싱글톤 패턴이란 클래스의 인스턴스가 하나만 있도록 하면서 이 인스턴스에 대해 Global Access Point를 제공하는 디자인 패턴이다.
싱글톤의 구현 방법은 아래와 같이 여러가지가 존재한다.
class Singleton private constructor() { companion object { private var INSTANCE: Singleton = Singleton() fun getInstance(): Singleton { return INSTANCE } } }
class Singleton private constructor() { companion object { private var INSTANCE: Singleton? = null fun getInstance(): Singleton { return INSTANCE ?: Singleton().apply { INSTANCE = this } } } }
class Singleton private constructor() { companion object { private var INSTANCE: Singleton? = null @Synchronized fun getInstance(): Singleton { return INSTANCE ?: Singleton().apply { INSTANCE = this } } } }
class Singleton private constructor() { companion object { @Volatile private var INSTANCE: Singleton? = null fun getInstance() = INSTANCE ?: synchronized(this) { INSTANCE ?: Singleton().apply { INSTANCE = this } } } }
- 인스턴스 생성 작업만 synchronized로 블럭킹 하는 방법이다.
- 메소드에 synchronized를 하게되면 호출이 많을 수록 성능이 떨어진다.
class Singleton private constructor() { companion object { class LazyHolder private constructor() { companion object { var INSTANCE = Singleton() } } fun getInstance() = LazyHolder.INSTANCE } }다음과 같은 형태가 있는데 사실 코틀린에서는 싱글톤을 구현할때 object만 사용하면 된다고 한다.
object Singleton {
fun somthing() {
}
}
fun main() {
Singleton.somthing()
}
다음과 같이 메서드를 호출할 수 있다.
출처
https://yoonda.tistory.com/36
https://dev-cho.tistory.com/63
전
후
전
후



발표도 끝나고 이제 다음 주부터 또 다른 챕터로 들어간다 ㅠㅠ
그래도 뭔가 좀 속 시원하다. 너무 힘든 한주였다.