brunch

You can make anything
by writing

C.S.Lewis

by 윤민섭 Nov 17. 2020

Delegation Pattern

나를 이용해라 패턴

Delegation 패턴은 어떤 객체에게 남의 도움을 받아도 되도록 만드는 패턴입니다.

그림을 먼저 보겠습니다.



먼저 Dependency 관계와 Implement 관계가 보입니다.


Object Needing a Delegate와 Delegate Protocol 이 Dependency 관계입니다.

Object Needing a Delegate는 Delegate가 필요한 객체이므로 Delegate Protocol을 소유합니다.

단, weak property로 delegate protocol을 소유함으로써 참조를 하지 않기 때문에 Association 관계가 아닌 Dependency 관계를 갖습니다.


Delegate Protocol에는 Object Needing a Delegate 객체가 필요한 부분을 정의합니다. 그리고 Implement 관계인 Object Acting as a Delegate 객체는 Delegate Protocol을 구현합니다.


이렇게 Object Needing a Delegate는 delegate protocol을 사용함으로써 구체적인 무언가에게 의존하지 않게 됩니다. 즉, 좀 더 유연 해지는 것이죠.


iOS에서는 대표적으로 UITableView, UICollectionView에서 Delegate 패턴을 사용합니다.

아래 코드를 보겠습니다.



UITableView는 애플에서 리스트를 보여주기 위해 만들어놓은 View 객체입니다. 하지만 List를 몇 개를 보여줄지 어떻게 보여줄지 결정하는 것은 개발자가 합니다. 모든 앱은 다 다르게 생겼기 때문이죠.


이런 정보를 담고 있는 protocol이 UITableViewDataSource입니다.

그리고 여기서 Object Needing a Delegate 객체는 UITableView가 됩니다.

Object Needing a Delegate는 Delegate Protocol과 Dependency 관계를 갖는다고 했습니다.



그렇기 때문에 UITableView에는 dataSource가 weak property로 구현되어있습니다.

그리고 우리는 Object Acting as a Delegate를 ViewController로 정하고 DataSource를 정의하며 UITableView에게 나를 이용하라 말하는 것이죠. (tableView.dataSource = self)


실제 현업에서도 Delegation Pattern은 다양하게 사용됩니다. 원리를 이해하고 사용하면 좋을 것 같습니다.

읽어주셔서 고맙습니다.




Raywenderlich의 Design Patterns by Tutorials를 참고했습니다.

https://www.raywenderlich.com/books/design-patterns-by-tutorials/v3.0


매거진의 이전글 MVC Pattern
작품 선택
키워드 선택 0 / 3 0
댓글여부
afliean
브런치는 최신 브라우저에 최적화 되어있습니다. IE chrome safari