생각보다 delegation pattern(d.p) 중요한 디자인패턴같다
우선 좋은 유튜브영상을 공유합니다
https://www.youtube.com/watch?v=JV1BKdz9hUA
d.p를 사용하면 특정 struct Data Fetch 하는개념을 Service라는 다른 클래스의 객체를 생성해서 진행할수있고 썸네일에 나와있는것처럼 4가지 편리함이 있다
struct ReservationPeople {
let count:Int
let name:String
}
protocol AppleStore {
func didFetchReservation(_ reservationPeople:ReservationPeople)
}
protocol GeniusBar {
var reservationPeople:ReservationPeople? {
get
}
}
class ReservationService {
var delegate: AppleStore?
var dataSource: GeniusBar?
func fetchReservation() {
guard let dataSource = dataSource else {
return
}
let reservationName = dataSource.reservationPeople?.name
let reservationCount = dataSource.reservationPeople?.count
let reservationPeople = ReservationPeople(count:reservationCount ?? 0, name:reservationName ?? "")
delegate?.didFetchReservation(reservationPeople)
}
}
struct KoreanAppleStore: AppleStore, GeniusBar {
let reservationService = ReservationService()
init() {
reservationService.delegate = self
reservationService.dataSource = self
}
func makeReservation() {
reservationService.fetchReservation()
}
func didFetchReservation(_ reservationPeople: ReservationPeople) {
print(reservationPeople.name)
print(reservationPeople.count)
}
var reservationPeople: ReservationPeople? {
let _name: String? = reservationPeople?.name
let _count:Int? = reservationPeople?.count
let _value = ReservationPeople(count: _count ?? 0, name: _name ?? "")
return _value
}
}
let reservationFirst = ReservationPeople(count: 3, name: "David")
let Garosulgill = KoreanAppleStore()
let reservationService = ReservationService()
Garosulgill.didFetchReservation(reservationFirst)
reservationService.fetchReservation()
let reservationSecond = ReservationPeople(count:5, name: "D-Park")
Garosulgill.didFetchReservation(reservationSecond)
reservationService.fetchReservation()
//출력값
David
3
D-Park
5