제라스의 iOS 공부/Swift 디자인 패턴

[Swift 디자인패턴] delegate 패턴을 알아보자

Xerath(제라스) 2023. 9. 17. 19:21
728x90
반응형

delegate...

delegate는 위임자라는 뜻이다. 어떤 것에 대한 대리자, 즉, 수행할 사람이란 거다. 밑에 코드를 한번 보자.

 

import UIKit

// 대리자에 대한 프로토콜
protocol RemoteControlDelegate {
    func channelUp()
    func channelDown()
}


// 리모콘 클래스(유저와 직접 대면함)
class RemoteControl {
    
    var delegate: RemoteControlDelegate? //사실상 여기에는 내가 이 리모콘으로 무엇을 작동할지 적는 것임.
    
    func doSomething() {
        print("리모콘의 조작이 일어나고 있음")
    }
    
    func channelUp() {   // 어떤 기기가 리모콘에 의해 작동되는지 몰라도 됨
        delegate?.channelUp()
    }
    
    func channelDown() {   // 어떤 기기가 리모콘에 의해 작동되는지 몰라도 됨
        delegate?.channelDown()
    }
}


// TV 클래스(리모콘과 커뮤니케이션하여 동작을 함.)
class TV: RemoteControlDelegate {
    
    func channelUp() {
        print("TV의 채널이 올라간다.")
    }

    func channelDown() {
        print("TV의 채널이 내려간다.")
    }

}

let remote = RemoteControl()
let samsungTV = TV()

remote.delegate = samsungTV



remote.channelUp()        // 리모콘 실행 ====> delegate?.channelUp()
remote.channelDown()      // 리모콘 실행 ====> delegate?.channelDown()





// SmartPhone 클래스(리모콘과 커뮤니케이션하여 동작을 함.)
class SmartPhone: RemoteControlDelegate {

    init(remote: RemoteControl) {
        remote.delegate = self       // remote.delegate = smartPhone
    }
    
    func channelUp() {
        print("스마트폰의 채널이 올라간다.")
    }
    
    func channelDown() {
        print("스마트폰의 채널이 내려간다.")
    }
}

let smartPhone = SmartPhone(remote: remote)
remote.channelUp()        // 리모콘 실행 ====> delegate?.channelUp()
remote.channelDown()      // 리모콘 실행 ====> delegate?.channelDown()

지금 클래스는 3개가 있다. RemoteControl, TV, SmartPhone.

이들의 관계는 이름부터 명시적이다. RemoteControl로 TV나 SmartPhone에 대한 동작을 제어하는 것이다. 즉 우리는 어떤 RemoteControl에 delegate(대표될 것)를 TV나 SmartPhone으로 지정해두면 그 RemoteControl 객체는 delegate에 지정된 것에 대한 것으로 적용이 되고 우리는 RemoteControl을 이용해서만 동작을 하면 되기에 RemoteControlDelegate 프로토콜을 채택한 하나의 객체만 지정해주면 된다.

 

일단은 이렇게 대충 간단한 예시만 공부를 했는데 아마 좀 더 알아가야 할 요소들이 있지 않을까 싶다. 그래도 이런 형태의 패턴이구나 하고 이해할 수 있어서 다행이다.

728x90
반응형