简体   繁体   中英

“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. 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. These three classes have a method called addContent that receives as an argument a String. Mail and Sentence have another method called addContent that receives a Word, and Mail has another addContent that receives a Sentence. On the side, all of them have a method called returnAsString that return the content as a string.

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). 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. 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

  • 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.

Any ideas?

Thanks

Your friend is Double Dispatch .

You will have to add a specialized addContent: method on each of the classes Mail, Sentence and Word. I give you the example for the combination Mail and 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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