- 싱글톤 패턴은 앱 실행 시, 힙 영역에 유일하게 한 개만 존재하는 객체가 필요한 경우에 사용한다.
- (특정, 유일한 데이터/관리 객체가 필요한 경우)
- 예시 코드
class Singleton {
static let shared = Singleton() // 자신의 객체를 생성해서 전역변수에 할당
// 왜 그냥 property가 아니라 static property일까?
// Singleton 패턴은 메모리에 단 하나의 객체만 올라가야 한다. 매번 인스턴스를 생성해야만 접근 가능한 stored property는 개념상 어긋(?)남
**var userInfoId = 12345**
private init() {}
}
사용 (접근) 방식
Singleton.shared.userInfoId
** private init을 정의하는 이유
싱글톤 패턴을 사용하더라도 매번 아래처럼 메모리에 또 다른 Singleton 인스턴스를 생성할 수 있다.
let singleton = Singleton()
이를 막기 위해 init 함수를 private으로 정의해서 유일한 접근 방식이 Singleton.shared로 강제하는 방식
- ios에서 실제 사용 예시
let screen = UIScreen.main // 화면
let userDefaults = UserDefaults.standard // 유저 디폴트
let application = UIApplication.shared // 앱
let fileManager = FileManager.default // 파일
let notification = NotificationCenter.default // 노티피케이션
'Design Pattern' 카테고리의 다른 글
SOLID Principles Series 5 : Dependency Inversion (의존성 역전 원칙) (0) | 2023.06.09 |
---|---|
SOLID Principles Series 2 : Open-Closed (개방 폐쇄 원칙) (0) | 2023.06.09 |
SOLID Principles Series 4 : Interface Segregation (인터페이스 분리 원칙) (0) | 2023.06.09 |
SOLID Principles Series 3 : Liskov Substitution(리스코프 치환) (0) | 2023.06.09 |
SOLID Principles Series 1 : Single Responsibility (단일 책임 원칙) (0) | 2023.06.09 |