본문 바로가기
iOS/Design Pattern

Design Pattern - Delegation Pattern

by HaningYa 2020. 8. 6.
728x90

Delegate: 대리자

Delegation Pattern 은 한 객체가 다른 Helper 객체를 통해 데이터를 전송하거나 특정 업무를 대신 할 수 있게 해주는 패턴이다.
(Delegation Pattern enables an object to use another "Helper" Object to provide data or perform a task rather than do the task itself)


Delegation Pattern 의 3가지 부분

  • Object needing a delegate: delegating object 라고도 한다. Delegate 를 가진 객체를 말하며 delegating 객체가 delegate 를 retain 할때 발생할 수 있는 retain cycle 을 피하기 위해 weak 프로퍼티로 묶여있다. 
  • delegate protocol: delegate 가 반드시 또는 선택적으로 구현되야 하는 메소드를 정의한다.
  • delegate: delegate protocol 을 구현한 helper object이다.

delegate protocol 을 통해 유연하게 implementation을 할 수 있다. 어느 object가 해당 protocol 을 준수한다면 delegate 가 될 수 있다.


언제 Delegation Pattern 을 써야할까

  • 큰 규모의 class 를 쪼갤때
  • 제너릭을 만들때
  • 재사용가능한 컴포넌트를 만들때

이 패턴은 Apple 프레임 워크에서 전반적으로 사용되는데 특히 UIKit에서 DataSource 와 Delegate 로 이름이 붙은 객체는 delegation pattern 을 따르고 각각은 다른 객체를 위해 데이터를 전달하거나 작업응 수행해주는 대리자 역할을 한다.

근데 DataSource 와 Delegate 로 왜 굳이 2개의 protocol 로 만들었을까. Apple 프레임워크에서 DataSource는 "데이터를 제공하는" delegate을 그룹화 한것이다. 예를들어 UITableViewDataSource의 경우 UITableViewCells를 화면에 표시하기 위해 사용된다.

Apple 프레임워크는 Delegate를 "데이터 또는 이벤트를 받는" delegate를 그룹화 한것이다. 예를들어 UITableViewDelegate는 테이블 뷰에서 어떤 row 가 선택되었는지 notify 해준다.

이렇게 따로 그룹을 지어서 나눠놓게 되면 각기 다른 objects에 대해 delegate 를 설정해야할 때 편하다.


Delegation Pattern 은 Behavioral Pattern 의 일종이다.

Delegation은 하나의 객체가 다른 객체와 communicating 하는 것이기 때문이다.


Custom Delegate & Protocol 만들기

 

Passing data between ViewControllers via Delegate & Protocols Swift 4.0

protocol , what is delegate , protocol in swift , protocol in swift 3.0, protocol in swift 4.0 ,What is the legal definition of protocol?, Using popViewController and passing data to the, delegate , protocol and delegate , data pass with delegate,Passing d

iosdevcenters.blogspot.com


Delegation Pattern 을 사용하며 주의할 점

  • 하나의 객체에 대해 너무 많은 delegate를 선언해서는 안된다.
    만약 한 객체가 너무 많은 delegate 를 가지고 있다면 그건 객체가 너무 많은 일을 하고 있다는 뜻이다. 그럴땐 객체를 기능별로 쪼개야 한다.
  • 만약 작업을 하면서 자꾸 class를 왔다갔다하는게 자주 일어나면 그것 또한 delegate 를 너무 많이 사용하고 있다는 증거이다.
    비슷하게 특정 delegate 가 왜 유용한지 모르겠다면 그건 너무 작게 쪼개서이다.
  • retain cycle을 만드는데도 주의해야 한다. 대부분의 delegate 프로퍼티는 weak 이다. 만약 객체가 무조건 delegate set을 가져야 한다면 delegate를 object initializer 에 넣고 forced unwrapping 하라. 이렇게 객체를 사용하기 전 강제로 consumers에게 delegate를 설정하게 할 수 있다.

 

728x90

'iOS > Design Pattern' 카테고리의 다른 글

Design Pattern - Singleton Pattern  (0) 2020.08.09
Design Pattern - Strategy Pattern  (0) 2020.08.07
Design Pattern - MVC  (0) 2020.07.14
Design Pattern - Class Diagram  (0) 2020.07.14
Design Pattern - Introduction  (0) 2020.07.14

댓글