Delegate Pattern

ddudios·2023년 12월 1일
3

iOS

목록 보기
1/1

Delegation: 위임

Delegate Pattern

하나의 객체가 처리해야할 일 중 일부를 다른 객체에게 넘기는 것 ( 위임 )

  • delegate는 어떤 객체의 대리자 ( 대리하다: 남을 대신해 일을 처리하다 )
    즉, 어떤 객체가 해야하는 일을 대신 처리한다
  • Delegate가 위임된 기능을 제공
  • 위임된 기능은 Protocol에서 정의

예시

TextField를 수정하기 시작하면 TextField가 노랑색으로 바뀐다

Delegate Pattern
( textField를 사용하는 class는 ViewController일 때 )

  • 하나의 객체가: TextField
  • 처리해야할 일 중 일부: TextField를 수정하기 시작하는 것을 감지
  • 다른 객체: ViewController
  • 에게 넘기는 것
  1. textField 객체가 ViewController를 대리자로 임명

    textField.delegate = self
  2. 대리자는 일을 수행하기 위해 그 기능이 정의되어 있는 프로토콜을 채택

    // 채택할 프로토콜: UITextFieldDelegate
    class ViewController: UIViewController, UITextFieldDelegate {
  3. UITextFieldDelegate에서 원하는 기능을 골라서 쓴다
    스크린샷 2023-12-01 오후 12 45 40https://developer.apple.com/documentation/uikit/uitextfielddelegate

    func textFieldDidBeginEditing(_ textField: UITextField) {
        textField.backgroundColor = .yellow
    }
  4. 전체 코드: https://github.com/ddudios/Velog/blob/main/DelegatePattern/DelegatePattern/ViewController.swift

  5. extension으로 코드 정리:
    https://github.com/ddudios/Velog/blob/main/DelegatePatternExtension/DelegatePattern/ViewController.swift

  6. 직접 Delegate Pattern을 구현해보기:
    https://github.com/ddudios/Velog/blob/main/DelegatePattern/DelegatePattern.playground/Contents.swift

장단점

활용도

결합도를 낮추면서 필요한 기능을 사용할 수 있다
객체간 data 전달할때 사용하기 좋다

0개의 댓글