Double dispatch in Pharo

杀马特。学长 韩版系。学妹 提交于 2020-01-22 19:45:08

问题


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:


Essentially the idea is that you have method:

  • #addInteger: which knows how to add integers,
  • #addFloat: which knows how to add floats,
  • and so on…

Now in Integer class you define + as:

+ otherObject

   otherObject addInteger: self

in Float you define it like:

+ otherObject

   otherObject addFloat: self

This way you only need to send + to an object and then it will ask the receiver to add it with the required method.

Another strategy is to use #adaptTo:andSend: methods. For example + in Point class is defined as:

+ arg 

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

Which first checks if the argument is a Point, and if it's not, asks the argument to adapt to Point and send some symbol (operation), this saves some duplication of the methods that have to perform a slightly different operation.

Collection implements the method like this:

adaptToPoint: rcvr andSend: selector

   ^ self collect: [:element | rcvr perform: selector with: element]

and Number implements it like that:

adaptToPoint: rcvr andSend: selector

   ^ rcvr perform: selector with: self@self

Note, that to avoid explicit type checking, we could define that method in the Point itself this way:

adaptToPoint: rcvr andSend: selector

   ^ (x perform: selector with: arg x) @ (y perform: selector with: arg y)

You can see more examples in this presentation: http://www.slideshare.net/SmalltalkWorld/stoop-302double-dispatch



来源:https://stackoverflow.com/questions/30851851/double-dispatch-in-pharo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!