Singleton의 생성자가 호출되는 시점

shintwl·2023년 11월 30일
0

싱글턴 패턴이 적용된 클래스/구조체의 객체를 반환하는 타입 프로퍼티가 호출될 때 생성자가 호출된다

간단한 테스트로 알아볼 수 있다

struct SingletonStruct {
    
    static let shared = SingletonStruct()

    private init() {
        print("SingletonStruct init called")
    }
}


let a = 10
let b = 20
print("timestamp 1")
print("timestamp 2")
print("timestamp 3")
let singleton = SingletonStruct.shared
print("timestamp 4")
print("timestamp 5")
print("timestamp 6")

/*
결과
timestamp 1
timestamp 2
timestamp 3
SingletonStruct init called
timestamp 4
timestamp 5
timestamp 6
*/

0개의 댓글