In OOP, what is forwarding and how is it different from delegation?

后端 未结 3 701
终归单人心
终归单人心 2021-02-02 11:21

Would someone please explain the difference between forwarding and delegation? They seem similar, but I haven\'t been able to find a good definition of forwarding, so I\'m not s

3条回答
  •  被撕碎了的回忆
    2021-02-02 11:31

    They're similar ideas in that one object relies on another for help. Here's how I think of the two ideas given my strong Objective-C bias:

    delegation: A decision needs to be made, but I don't want to make it. I'll let my delegate handle that.

    In Cocoa, for example, NSTableView uses a delegate to customize the behavior of the table. Delegation provides a way to customize one object by letting another object, the delegate, provide the customization. Continuing with the example, a table view's delegate implements an NSTableViewDelegate interface that the table uses to talk to its delegate.

    forwarding: Someone just sent me a message that I don't understand, but I know of another object that might implement it. I'll pass the invocation of that message on to that object.

    In Cocoa, again, any class can implement the -forwardInvocation: method. If a message is sent to an object that doesn't implement it, that object's -forwardInvocation: method is called, and the object can decide to pass the invocation on to another object. That object could be its delegate, or it could be some system-wide error handler, or whatever. NSProxy uses this to appear to implement all methods -- it just passes the invocation on to its master object.

    Note that with forwarding, there's not a defined delegate interface; the message is just passed on to another object. Another place you see what I'd call forwarding is when one object contains another object that it uses to implement some interface. Any messages to that interface are just forwarded to the contained object, which does all the work.

提交回复
热议问题