Search code examples
iosswiftdelegation

Can delegation be implemented in any language or it is language specific


I'm currently trying to understand the delegation pattern and I was wondering if this pattern is language specific, in other words does the language need to have some sort of support for Protocols, Interfaces etc. in order for this pattern to work or it can be implemented in any language?

Swift Example:

protocol SendersMessageDelegate{
    func shareMessage(message: String)
}

class Sender{
    var sendersMessage: String = String()
    var delegate: SendersMessageDelegate?

    func sendMessage(sendersMessage: String) {
        self.sendersMessage = sendersMessage
        delegate?.shareMessage(sendersMessage)
    }
}


class Receiver: SendersMessageDelegate{

    var savedMessage:String?

    func shareMessage(message: String) {
        savedMessage = message
        print(message)
    }
}

var sender = Sender()
var receiver = Receiver()

sender.delegate = receiver

sender.sendMessage("Hello Receiver"

)

Solution

  • Protocols / interfaces allow you to create a clean and generic specification of the interface between the classes involved, but they aren't required. Generally the delegating class knows nothing about the delegate other than that it responds to a set of methods, but again that isn't required - often there are explicit runtime tests to check if it responds to the target methods or not. Strictly speaking it also doesn't need to be classes.

    So, any language where you can have multiple code files / 'objects' which refer to another could be described as a delegate relationship. The difference between delegation and composition or simple invocation can be woolly. Abstract interfaces help tip the scale towards delegation.