lgvv98

[Swift] Delegation Pattern 본문

apple/DesignPattern & Architecture

[Swift] Delegation Pattern

lgvv 2022. 4. 10. 21:18

Delegation Pattern

 

✅ Delegation Pattern

 

아래의 문서를 구입하여 직접 번역 및 정리합니다. 

https://www.raywenderlich.com/books/design-patterns-by-tutorials/v3.0/chapters/4-delegation-pattern

 

Design Patterns by Tutorials, Chapter 4: Delegation Pattern

The delegation pattern enables an object to use another “helper” object to provide data or perform a task rather than the task itself. By relying on a delegate protocol instead of a concrete object, the implementation is much more flexible: any object

www.raywenderlich.com

 

 

Delegation Pattern 

 딜리게이트 패턴을 이용하여 직접 작업을 수행하는 대신 helper 개체를 이용하여 데이터를 제공하거나 작업을 대신 수행합니다.

딜리게이트 패턴에는 세 부분이 있습니다.

3가지 부분

 

🟠 Object needing a delegate (a.k.a delegate object) 

 - delegate를 가지는 객체이며, delegate를 ratain cycle을 피하기 위해서 weak property로 들고 있습니다.

🟠 Delegate Protocol 

 - delegate가 구현할 수 있거나(optional) 구현해야 하는 메소드를 정의하는 프로토콜을 말합니다.

🟠 Object Acting as a Delegate

 - delegate 프로토콜을 구현하는 helper 객체입니다.

 

구체적인 객체 대신에 delegate를 프로토콜에 의존함으로써 구현을 더 유연하게 할 수 있다.

 

 

✅ When should you use it?

 

큰 클래스 또는 create generic(재사용 가능한 컴포넌트들)를 분리할 때 사용합니다. 애플의 UIKit을 일반적으로 delegate 패턴을 따르고 있습니다. DataSource, Delegate라는 이름이 붙은 객체들은 실제로는 딜리게이트 패턴을 따릅니다. 왜냐하면 다른 객체에게 데이터를 제공하거나 무언가 작업을 수행하도록 요청하기 때문입니다. 

 

애플의 프레임워크의 프로토콜 네이밍 규칙에서 Delegate는 주로 이벤트를 수신하는데 메소드 붙으며, DataSource는 데이터를 제공하는데 이용어를 사용합니다.

 

Tutorial project

아래 코드에 주석으로 상세히 적어두었습니다.

 

코딩 기법이나 트릭 등 배울 점이 정말 많은 예제입니다. 꼭 참고하여 보시길 바랍니다. 

 

https://github.com/lgvv/DesignPattern/tree/main/delegation-pattern/RabbleWabble

 

GitHub - lgvv/DesignPattern: ✨ 디자인 패턴을 공부합니다!

✨ 디자인 패턴을 공부합니다! Contribute to lgvv/DesignPattern development by creating an account on GitHub.

github.com

 

아래는 위의 소스코드를 직접 클래스 다이어그램으로 그린 부분입니다.

delegation pattern class diagram

 

 

✅ KeyPoint

우리는 이번 챕터에서 애플에서 제공하는 delegates를 사용하는 방법과 delegate를 만드는 방법을 포함하여 delegation pattern에 대해서 배웠다.  

(핵심사항) 

- 딜리게이션 패턴은 세 부분으로 구성되는데, an object needing a delegate, delegate protocol and delegate으로 구성된다. 

- 이 패턴은 큰 클래스나 create generic(재사용 가능한 컴포넌트들)을 분리하는데 사용함 

- delegate는 weak properties로 들고 있어야 한다. 

 

 

 

 

 

'apple > DesignPattern & Architecture' 카테고리의 다른 글

[Swift] Observer Pattern  (0) 2022.04.19
[Swift] Memento Pattern  (0) 2022.04.13
[Swift] Strategy Pattern  (0) 2022.04.11
[Swift] MVC Pattern  (0) 2022.04.08
[Swift] Class Diagram + 스터디  (0) 2022.04.07
Comments