开发者

Significant difference between delegation and notification

I am reading 开发者_高级运维the Cocoa Fundamentals->Design Patterns->Observer->Uses and Limitations. It mentioned a "significant difference from delegation" that confuses me:

But objects receiving notifications can react only after the event has occurred. This is a significant difference from delegation. The delegate is given a chance to reject or modify the operation proposed by the delegating object. Observing objects, on the other hand, cannot directly affect an impending operation.

Especially on delegate is given a chance to reject or modify the operation, while observing objects can not.


Delegation means that the other object is called to perform a given task, so naturally it has a chance to influence the outcome of that task. It is like your friend asking you to buy 2 movie tickets for tonight - you have a say where to go, what movie to watch, may even suggest inviting more friends or go to a concert instead.

Notification happens only after the task has been performed, so the notified object can not change the event anymore. It is like your friend saying "I have 2 tickets for Avatar at 8pm tonight in Palace Cinema, would you like to come?".


@Péter's answer is absolutely correct. I'd like to add a bit more information:

  • An object can only have one delegate. However, many objects can listen to notifications from a single object. Notifications are "broadcasted" to the entire application, and anybody who wants to can listen to the notification and react to it.
  • Delegate methods can have a return value. In other words, they can return some value other than (void). Notification methods cannot return any object, because they have no object to return to.
  • Delegate methods are invoked immediately, whereas notifications are usually delayed until the next loop through the run loop. This means that objects can use their delegates to retrieve information immediately before continuing. This is the main reason why delegates are so useful. You can ask them for information and they will immediately respond with it.


Matt Gallagher wrote about 5 approaches to listening and observing which might give another perspective.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜