Delegate 패턴
Delegate 패턴은 객체지향 프로그래밍에서 자주 사용되는 디자인 패턴 중 하나로, 하나의 객체가 다른 객체의 동작을 대신 처리하도록 위임하는 방식입니다. Swift에서는 주로 프로토콜과 함께 사용됩니다. Delegate 패턴은 주로 어떤 이벤트가 발생했을 때 특정 작업을 처리하기 위해 사용됩니다.
Delegate 패턴의 구성 요소
- Delegate 프로토콜: 특정 동작을 정의하는 프로토콜입니다.
- Delegate: 프로토콜을 채택하고 구현하는 객체입니다.
- Delegator: 동작을 위임하는 객체로, 보통 delegate 프로퍼티를 통해 Delegate 객체에 대한 참조를 가지고 있습니다.
Delegate 패턴의 장점
- 모듈화: 코드가 잘 분리되어 모듈화됩니다.
- 유연성: 다양한 객체가 동일한 동작을 다른 방식으로 구현할 수 있습니다.
- 재사용성: 코드의 재사용성이 높아집니다.
예시 코드
다음은 iOS에서 Delegate 패턴을 사용하는 간단한 예제입니다. 이 예제에서는 CustomView라는 클래스가 버튼 클릭 이벤트를 Delegate에게 알리는 상황을 가정합니다.
1. Delegate 프로토콜 정의
먼저, 버튼 클릭 이벤트를 처리할 프로토콜을 정의합니다.
import UIKit
protocol CustomViewDelegate: AnyObject {
func didTapButton()
}
2. Delegator 클래스 정의
다음으로, 버튼 클릭 이벤트를 발생시키는 CustomView 클래스를 정의합니다.
import UIKit
class CustomView: UIView {
weak var delegate: CustomViewDelegate?
private let button: UIButton = {
let button = UIButton(type: .system)
button.setTitle("Tap me", for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setupView()
}
private func setupView() {
addSubview(button)
button.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
button.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
}
@objc private func buttonTapped() {
delegate?.didTapButton()
}
}
3. Delegate 구현
이제 CustomViewDelegate 프로토콜을 채택하고 구현하는 ViewController 클래스를 작성합니다.
import UIKit
class ViewController: UIViewController, CustomViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let customView = CustomView(frame: view.bounds)
customView.delegate = self
view.addSubview(customView)
}
func didTapButton() {
print("Button was tapped!")
}
}
작동 방식
- ViewController는 CustomViewDelegate 프로토콜을 채택하고 didTapButton 메서드를 구현합니다.
- ViewController는 CustomView의 delegate로 설정됩니다.
- CustomView에서 버튼이 클릭되면 delegate?.didTapButton()을 호출하여 ViewController의 didTapButton 메서드를 실행합니다.
이 예제에서 Delegate 패턴은 CustomView와 ViewController 간의 결합도를 낮추면서도 CustomView가 버튼 클릭 이벤트를 처리할 수 있도록 합니다. 이를 통해 코드의 유연성과 재사용성이 높아집니다.
반응형
'TIL (Today I Learned)' 카테고리의 다른 글
[TIL] 2024. 07. 10 (0) | 2024.07.10 |
---|---|
[TIL] 2024. 07. 09 (0) | 2024.07.09 |
[TIL] 2024. 07. 05 (0) | 2024.07.06 |
[TIL] 2024. 07. 04 (0) | 2024.07.04 |
[TIL] 2024. 07. 03 (0) | 2024.07.03 |