Double dispatch in Pharo

时间:2015-06-15 17:56:28

标签: smalltalk pharo double-dispatch

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.

1 个答案:

答案 0 :(得分:13)

基本上这个想法是你有方法:

  • #addInteger:知道如何添加整数,
  • #addFloat:知道如何添加花车,
  • 等......

现在在Integer课程中,您将+定义为:

+ otherObject

   otherObject addInteger: self
{p}在Float中您将其定义为:

+ otherObject

   otherObject addFloat: self

这样你只需要将+发送给一个对象然后它会要求接收者用所需的方法添加它。

另一种策略是使用#adaptTo:andSend:方法。例如,+类中的Point定义为:

+ arg 

   arg isPoint ifTrue: [^ (x + arg x) @ (y + arg y)].
   ^ arg adaptToPoint: self andSend: #+

首先检查参数是否为Point,如果不是,请求参数适应Point并发送一些符号(操作),这样可以节省一些必须执行略微不同操作的方法的重复。 / p>

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