Smalltalk中的消息转发 [英] Message forwarding in Smalltalk
问题描述
因此,我正在编写一个应用程序,其中一个对象具有一堆将消息转发到的委托对象.我的想法是我可以说
So I'm writing an application where one object has a bunch of delegate objects that it forwards messages to. The idea is that I can say
someObject sendMessage:aMessage
和aMessage将被发送到someObject的所有委托(对于aMessage的任何值).我能够做到这一点的唯一方法是:
and aMessage will be sent to all of someObject's delegates (for any value of aMessage). The only way I've been able to do this is something like:
sendMessage:aMessage
| sel chunks kwords arglist msg |
chunks := aMessage findTokens:' '.
kwords := Array new:(chunks size).
arglist := Array new:(chunks size).
1 to: (chunks size) do: [:i |
kwords at:i put:((chunks at:i) findTokens:':') at:1.
arglist at:i put:((chunks at:i) findTokens:':') at:2].
sel := ''.
kwords do:[:word | sel := sel,word,':'].
msg := Message selector:sel arguments:arglist.
delegates do:[:del | del perform:msg selector with:msg arguments].
它可以工作,但是必须有更好的方法.该解决方案将参数限制为字符串,这很丑陋.有谁知道一种更干净,更好的邮件转发方式?
It works, but there has to be a better way. This solution limits the arguments to being strings, and is just plain ugly. Does anyone know a cleaner, better way to forward messages?
顺便说一句,我正在使用吱吱声,但最好采用与实现无关的解决方案;)
BTW, I'm using squeak, but an implementation-independent solution would be prefered ;)
编辑:我应该补充一下,这些委托与该对象属于同一类,所以我不能仅仅覆盖DidsNotUnderstand:.
EDIT: I should add that the delegates are of the same class as the object, so I can't just override DoesNotUnderstand:.
推荐答案
由于要将对象作为参数传递,因此必须将它们作为使用如下消息模式的单独列表传递:>
Since you want to pass objects in as arguments, you'll have to pass them in as a separate list of using a message pattern like the following:
someObject sendMessage:带参数的aSelector:argumentsList
someObject sendMessage: aSelector withArguments: argumentList
然后您将#sendMessage:withArguments:实现为:
Then you'd implement #sendMessage:withArguments: as:
sendMessage:带有参数的aSelector:argumentList
sendMessage: aSelector withArguments: argumentList
代表行事:[:del | 删除执行:aSelector withArguments::argumentList].
delegates do:[:del | del perform: aSelector withArguments: :argumentList].
,您将能够使用真实对象作为args转发任意复杂的消息:
and you'd be able to forward arbitrarily complex messages using real objects as args:
|参数|
| arguments |
参数:=数组 使用:新对象 与:1234.5 带有:(键"->值").
arguments := Array with: Object new with: 1234.5 with: ('key'->'value').
someObject sendMessage:#foo:bar:baz:withArguments:arguments
someObject sendMessage: #foo:bar:baz: withArguments: arguments
我认为这对于大多数方言也是可移植的...
I think this is portable to most dialects as well...
这篇关于Smalltalk中的消息转发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!