Could someone please explain the process of double dispatch in Pharo 4.0 with Smalltalk? I am new to Smalltalk and am having difficulty grasping the concept, since it is implemented very differently in Java as compared to Smalltalk. It will be very helpful if some one could explain it with an example.
问问题
1471 次
1 回答
13
本质上,这个想法是你有方法:
#addInteger:
它知道如何添加整数,#addFloat:
它知道如何添加浮点数,- 等等……</li>
现在在Integer
课堂上你定义+
为:
+ otherObject
otherObject addInteger: self
在Float
你定义它像:
+ otherObject
otherObject addFloat: self
这样你只需要发送+
到一个对象,然后它会要求接收者使用所需的方法添加它。
另一种策略是使用#adaptTo:andSend:
方法。例如+
在Point
类中定义为:
+ arg
arg isPoint ifTrue: [^ (x + arg x) @ (y + arg y)].
^ arg adaptToPoint: self andSend: #+
首先检查参数是否为 Point,如果不是,则要求参数适应 Point 并发送一些符号(操作),这样可以节省一些必须执行稍微不同的操作的方法的重复。
Collection
实现这样的方法:
adaptToPoint: rcvr andSend: selector
^ self collect: [:element | rcvr perform: selector with: element]
并Number
像这样实现它:
adaptToPoint: rcvr andSend: selector
^ rcvr perform: selector with: self@self
请注意,为了避免显式类型检查,我们可以通过这种方式在Point
自身中定义该方法:
adaptToPoint: rcvr andSend: selector
^ (x perform: selector with: arg x) @ (y perform: selector with: arg y)
您可以在此演示文稿中看到更多示例:http ://www.slideshare.net/SmalltalkWorld/stoop-302double-dispatch
于 2015-06-15T22:55:15.660 回答