9

我对 Objective-C 相当陌生,但在 Java 方面经验丰富。Java中是否有Objective-C“委托”的等效概念,以便我可以更好地理解这个概念?有没有办法在 Java 中模拟委托概念?

4

4 回答 4

9

委托只是一种避免像表视图这样的对象子类化来实现应用程序特定行为的方法,而是将责任放在控制器上。当您创建表视图时,您为其分配了一个控制器对象,该对象实现了一组定义的方法(一些可能是必需的,其他可能是可选的)。当表视图需要数据或必须决定如何显示自己时,它会询问委托是否实现了适当的方法,如果实现则调用它来做出决定。

于 2009-01-14T21:13:13.027 回答
4

Here's a way to think of a delegate - in the OOP typical example, I have a car object. I don't want to ever subclass it again, I just want to use it as is, so how do I make it act like a chevy or a mustang? I give it a delegate.

My car would have methods to drive, methods to honk, etc.

My delegate would have methods like "what's my top speed" and "what does the horn sounds like" and "are my windows tinted"

So when I call -drive on my car object, (which isn't subclassed) that method calls my delegate's topSpeed method, and the delegate tells it 120mph, so the car knows how fast it should go without having to be a mustang.

in Objective C there's usually a protocol that defines what a delegate should respond to, i.e. for my car object's delegate there would be a protocol declared like this:

 @protocol carDelegate

 -(int)carTopSpeed;
 -(UIColor*)carColor;
 -(BodyShape*)carBodyShape;
 -(DragCoefficient*)carDragCoefficient;
 -(HoodOrnament*)carHoodOrnament     

 @optional
 -(BOOL)windowsTinted;

 @end

Then you can make your own object that conforms to this protocol (implements all the required methods, and any optional ones that are seen as needed)

And the car object would expect an (id) to be passed to it as a delegate.

Then the car object has managed to avoid being subclassed, and still can behave according to the user's needs.

于 2010-10-20T22:57:14.473 回答
3

java.lang.reflect.Proxy是java中最接近的等价物。虽然使用起来很乏味。

于 2009-01-14T21:18:21.767 回答
2

委托是一种面向对象的设计模式。Wikipedia 上有一个 Java 示例:委托模式

于 2009-01-14T20:46:55.997 回答