How delegation works?

For delegation to occur in software, one has to have a situation where one class (the delegator class) would give control or responsibility for some behavioural logic to another class called a delegate.

So how does a class assign responsibilities to another class? By using [protocols][Apple Dev Protocols].

Protocols

Apple defines protocols as following

A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality.

Protocols as blueprints

Protocols are an abstraction layer and do not provide implementation details in their declaration... only function and property names. Like a blueprint. With a single blueprint, thousands of homes can be constructed using slightly different construction materials or processes. So too with a protocol. Many classes can be built to adopt a protocol's specification. Such classes may choose to implement the protocol spec in their own unique ways, but they all will still be defining the behaviour the protocol specifies.

Protocols as contracts

Protocols are similar to contracts. A contract is a thing in the middle of two parties who are trying to negotiate a deal. To one party, the contract is a guarantee of some terms that will be satisfied. To the other party, the contract is a set of obligations.

In the delegation design pattern, protocols serve the same kind of middle-man role as a contract. To the delegator class, the protocol is a guarantee that some of the behaviour (methods & properties) will be supplied by the delegate class. To the delegate class, the protocol is a set of obligation - a set of methods and properties it must define when it adopts the protocol ("signs the contract").

Listing the players

So we can now see three players involved in the delegation design process:
+ a protocol defining the responsibilities that will be delegated + a delegator, which depends on an instance of something conforming to that protocol + a delegate, which adopts the protocol and implements its requirements

Visualise the players

Delegate_Environment

Next read: An example in code: Delegation

Animesh.

Read more posts by this author.

United Kingdom

Subscribe to Animesh.

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!