Smalltalk 中的消息转发 [英] Message forwarding in Smalltalk

查看:32
本文介绍了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?

顺便说一句,我正在使用 squeak,但首选独立于实现的解决方案 ;)

BTW, I'm using squeak, but an implementation-independent solution would be prefered ;)

编辑:我应该补充一点,委托与对象属于同一类,所以我不能只覆盖DoesNotUnderstand:.

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 withArguments:argumentList

someObject sendMessage: aSelector withArguments: argumentList

然后你会实现 #sendMessage:withArguments: as:

Then you'd implement #sendMessage:withArguments: as:

sendMessage:aSelector withArguments:argumentList

sendMessage: aSelector withArguments: argumentList

代表做:[:del |del perform: aSelector withArguments: :argumentList].

delegates do:[:del | del perform: aSelector withArguments: :argumentList].

并且您可以使用真实对象作为参数转发任意复杂的消息:

and you'd be able to forward arbitrarily complex messages using real objects as args:

|参数|

参数 := 数组与:对象新与:1234.5使用:('key'->'value').

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆