[iOS 4주차] 디자인 패턴

황석범·2024년 11월 13일
2

내일배움캠프_iOS_5기

목록 보기
19/76

Swift에서의 디자인 패턴

  • 디자인 패턴은 코드 구조를 효율적으로 설계하고 유지 관리하기 위해 자주 사용하는 코드 구조

1. 싱글톤(Singleton)

  • 애플리케이션에서 하나의 인스턴스만 존재하도록 보장하는 패턴입니다. 공통된 자원이나 설정을 여러 클래스에서 사용할 때 유용합니다.
    • ex) 네트워크 매니저, 데이터베이스 연결, 앱 설정 관리 등
class SingletonExample {
    static let shared = SingletonExample()
    private init() { }
}

2. 팩토리 패턴(Factory Pattern)

  • 객체 생성을 별도의 클래스에서 처리하여 클라이언트가 객체 생성 방식을 알 필요 없도록 하는 패턴입니다.
    • ex) 네트워크 요청 객체, 커스텀 뷰 생성시

protocol Product {
    func use()
}

class ConcreteProductA: Product {
    func use() { print("Using Product A") }
}

class ConcreteProductB: Product {
    func use() { print("Using Product B") }
}

class Factory {
    static func createProduct(type: String) -> Product? {
        switch type {
        case "A":
            return ConcreteProductA()
        case "B":
            return ConcreteProductB()
        default:
            return nil
        }
    }
}

3. 델리게이트 패턴(Delegate Pattern)

  • 특정 작업을 다른 객체에 위임하여 코드의 재사용성을 높이고 유지관리를 쉽게 만드는 패턴입니다.
    • ex) UITableView나 UICollectionView

protocol TaskDelegate: AnyObject {
    func didCompleteTask()
}

class TaskManager {
    weak var delegate: TaskDelegate?
    
    func startTask() {
        // 작업 수행
        delegate?.didCompleteTask()
    }
}

class TaskHandler: TaskDelegate {
    func didCompleteTask() {
        print("Task completed")
    }
}

4. 옵저버 패턴(Observer Pattern)

  • 특정 객체의 상태가 변경되었을 때 관련된 객체들에게 알림을 주는 패턴입니다.
    • ex) NotificationCenter, KVO(Key-Value Observing)

class NotificationExample {
    init() {
        NotificationCenter.default.addObserver(self, selector: #selector(handleNotification), name: .exampleNotification, object: nil)
    }
    
    @objc func handleNotification() {
        print("Notification received")
    }
}

extension Notification.Name {
    static let exampleNotification = Notification.Name("exampleNotification")
}

5. MVC(Model-View-Controller)

  • 데이터를 처리하는 모델, 사용자 인터페이스인 뷰, 로직을 처리하는 컨트롤러로 구분하여 애플리케이션의 구조를 나누는 패턴입니다.
    • ex) UIKit 기반의 iOS 앱에서 많이 사용됩니다.
  • 모델, 뷰, 컨트롤러 각각의 클래스를 만들어 책임을 나눕니다.
  • 예를 들어 Model 클래스는 데이터 관리, View 클래스는 UI 표시, Controller 클래스는 로직 처리.

6. MVVM(Model-View-ViewModel)

  • MVC의 대안으로, UI 상태와 로직을 ViewModel에서 처리하여 View와 Model의 의존성을 줄이는 패턴입니다.
    • ex) SwiftUI와 Combine을 함께 사용하는 경우 효과적입니다.
  • Model: 데이터 구조와 비즈니스 로직
  • ViewModel: 데이터를 가공하여 View에 전달
  • View: UI를 표시하고 ViewModel과 바인딩하여 업데이트

Swift에서 이와 같은 디자인 패턴을 적용하면 코드의 가독성, 재사용성, 유지보수성이 높아집니다. 각 패턴은 상황에 맞게 유연하게 사용될 수 있으며, 특히 SwiftUI와 Combine을 사용한 MVVM 패턴은 최신 앱 개발에서 많이 채택되고 있습니다.

profile
iOS 공부중...

0개의 댓글

관련 채용 정보