Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a doubledispatch for the instance creation method?

instance creation method, like

ClassName new

To aid with some details,

we could write a = arithmetic method in abstract class,

then doubledispatch them in subclasses.

could we use that in instance creation?

I have tried new but it fail. Leads to some predefined basic new method.

like image 904
marsrover Avatar asked Jan 31 '26 21:01

marsrover


2 Answers

Double Dispatch doesn't really make sense in the new case. The idea behind double dispatch, is that you can't determine the correct behavior by dispatching only to the receiver. The type of the (single) argument has an equal effect on which behavior is chosen (dispatched). In other words, double dispatch only makes sense if you have arguments to your methods, new being unary, it does not.

That said, you can certainly implement your own new method that overrides the stock default inherited one. And you can make it do all kinds of interesting things. It's common to do some sort of environment check to determine what subclass is appropriate.

AbstractClass>>>new
    ^self platform = #unix
        ifTrue: [SubclassThatLeveragesUnix basicNew]
        ifFalse: [CrappyPCSubclass basicNew]

Note that we use basicNew here, rather than new. If you used new you would need to either implement distinct overrides in those subclasses, otherwise it would just inherit and resend the AbstractClass>>>new message again.

like image 141
Travis Griggs Avatar answered Feb 03 '26 14:02

Travis Griggs


... or you could do something like:

AbstractClass class>>#new 
    ^ (self platform concreteClassFor: self) basicNew initialize.

which is basically same idea, but without ifs :)

like image 22
EstebanLM Avatar answered Feb 03 '26 13:02

EstebanLM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!