简体   繁体   English

Smalltalk中“重载”方法是否根据参数的类?

[英]“Overloading” method in Smalltalk according to parameter's class?

I know you can't overload a method in Smalltalk according to the parameter's class. 我知道您无法根据参数的类在Smalltalk中重载方法。 I am left with this design problem: 我剩下这个设计问题:

I have three classes: one that implements a Mail, one that implements a Sentence and one that implements a Word. 我有三类:一类实现邮件,一类实现句子,一类实现Word。 These three classes have a method called addContent that receives as an argument a String. 这三个类都有一个名为addContent的方法,该方法接收String作为参数。 Mail and Sentence have another method called addContent that receives a Word, and Mail has another addContent that receives a Sentence. Mail和Sentence具有另一种称为addContent的方法来接收Word,而Mail具有另一种addContent来接收句子。 On the side, all of them have a method called returnAsString that return the content as a string. 一方面,它们都具有一个名为returnAsString的方法,该方法以字符串形式返回内容。

I am left to the following possibilities: 我有以下可能性:

  • Implement them through dependencies: Mail has a collection of Sentence and Sentence has a collection of Word (and Word just has a string). 通过依赖关系实现它们:Mail具有Sentence的集合,而Sentence具有Word的集合(而Word仅具有字符串)。 Then that addContent could be implemented by asking the parameter to return its contents in a string, and make the object's attribute use the addContent(String) to load it. 然后可以通过要求参数以字符串形式返回其内容来实现addContent,并使对象的属性使用addContent(String)进行加载。 The problem I find with this approach is that I'd have to add a method for a String object to return itself as a String, and for the rest that method should be returnAsString 我发现这种方法的问题是,我必须为String对象添加一个方法以将自身返回为String,其余的方法应该为returnAsString

  • Make them all inherit form a base abstract class. 使它们全部继承一个基本抽象类。 I just don't know how this would work, because I'd also make Word have a method to addContent through a Sentence, and that is wrong. 我只是不知道这将如何工作,因为我还将使Word具有通过句子添加内容的方法,这是错误的。

Any ideas? 有任何想法吗?

Thanks 谢谢

Your friend is Double Dispatch . 您的朋友是Double Dispatch

You will have to add a specialized addContent: method on each of the classes Mail, Sentence and Word. 您将必须在Mail,Sentence和Word的每个类上添加专门的addContent:方法。 I give you the example for the combination Mail and String. 我给您结合Mail和String的示例。

Mail >> addContent: content
    content addToMail: self

String  >> addToMail: mail
    mail addStringContent: self

Mail >> addStringContent: aString
   "here you have the explicit type encoded in the selector"
   self todo: 'Add a string to the mail"

Similarly you can fix the combinations for adding Strings to Sentences, Words to Sentences, and Sentences to Mails. 同样,您可以修复将字符串添加到句子,单词添加到句子以及句子添加到邮件的组合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM