Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

# 싱글톤패턴 Singleton Pattern #25

Open
yoogail105 opened this issue Apr 20, 2022 · 0 comments
Open

# 싱글톤패턴 Singleton Pattern #25

yoogail105 opened this issue Apr 20, 2022 · 0 comments

Comments

@yoogail105
Copy link
Owner

yoogail105 commented Apr 20, 2022

# 싱글톤패턴 Singleton Pattern

  • 특정 용도로 객체를 하나만 생성하여, 공용으로 사용하고 싶을 때 사용하는 디자인유형
    • 하나의 인스턴스를 메모리에 등록하여, 여러 스레드가 동시에 공유
    • 하나만 생성: 이 클래스에 대한 인스턴스는 최초 생성될 때 한번만 생성
    • 공용으로: 전역에서, 모든 클래스에서 접근 가능

사용

  • 생성

    class UserInfo {
        **static let shared = UserInfo()**
        
        var id: String?
        var pass: String?
        var name: string?
    
    		**private init() { }**
    }
    • static 프로퍼티에 인스턴스 생성
    • init함수 접근제어자 private으로 지정 private init() { }
      → init 함수 호출을 통해 또 다른 인스턴스 생성을 방지
    • 클래스를 정의할 때 내부에, 해당 클래스와 같은 타입의 타입프로퍼티를 생성
      → 객체를 생성하지 않아도, 접근이 가능하도록
  • 접근: static프로퍼티를 통해 접근

    let userInfo = UserInfo.shared
    userInfo.id = "bbu"
  • 예시

    let screen = UIScreen.main
    let userDefaults = UserDefaults.standard
    let application = UIApplication.shared
    let fileManager = FileManager.default
    let notification = NotificationCenter.default
    let sharedURLSession = URLSession.shared

장단점

장점

  • 인스턴스를 한 번만 생성 → 메모리 낭비 방지
  • 전역 인스턴스→ 다른 클래스들과 자원 공유 용이
  • 전역 변수와 똑같은데 싱글턴을 사용하는 이유?
    • 싱글턴은 생성하는 시점부터 메모리를 사용한다. 생성되기 전에는 메모리에 올라가지 않음(lazy한 타입프로퍼티의 특성)
  • ?? DBCP(DataBase Connection Pool) 처럼 공통된 객체를 여러개 생성해서 사용해야 하는 상황에서 많이 쓰임(쓰레드풀, 캐시, 대화상자, 사용자설정, 등)

단점

  • 싱글턴인스턴스가 너무 많은 일 or 너무 많은 데이터를 공유 → 다른 클래스 간 결합도가 높아져 개방폐쇄 원칙을 위배(기능을 수정, 추가하는 데에 기존의 코드를 수정해야하는 상황 발생)
    → 수정, 테스트 어려워짐

특징 thread-safe? (feat. type property)

  • thread-safe하지 않은 환경에서 singleton을 생성하면, 동시에 여러 개의 싱글톤 인스턴스가 생성될 수 있음 → 이는 더 이상 싱글톤이 아님.

  • swift: static을 사용해 타입 프로퍼티로 인스턴스 생성 → 사용시점에 초기화(lazy)

    싱글톤 인스턴스가 최초 생성되기 전까지는 메모리에 올라가지 않고(lazy), 한 번 생성되면 그 뒤로는 생성되지 않는 objc의 dispatch_once도 자동으로 적용된다.(dispatch_once: 앱 실행되고 단 한 번만 실행되도록 제어)

  • 싱글톤을 생성할 때 thread-safe하게 동작

🔖참고

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant