开发者

What is Method Dispatch?

开发者 https://www.devze.com 2022-12-12 11:21 出处:网络
What is Method Dispatch?I can find several concrete examples, but an abstract definition of method dispatch eludes me.An开发者_开发知识库yone care to venture theirs?First let\'s say what a message and

What is Method Dispatch? I can find several concrete examples, but an abstract definition of method dispatch eludes me. An开发者_开发知识库yone care to venture theirs?


First let's say what a message and a method are:

  • A message is a name that can be sent from one object to another, possibly with additional objects as arguments. For example in

    account withdraw: 100
    

    The message is withdraw: (Smalltalk syntax.) (Other languages might write account.withdraw(100).) The object receiving the message, in this example account, is called the receiver.

  • A method is an implementation that can be invoked in response to a message.

These ideas are shared among a wide variety of object-oriented languages, sometimes under different names. For example, C++ calls a message a 'virtual member function'.

Now:

  • Method dispatch is the algorithm used to decide which method should be invoked in response to a message. Algorithms vary dramatically across languages:

    • Languages like Smalltalk, which have classes and single inheritance, consult the class of the receiver. If the method is defined on that class, that method is invoked. Otherwise the algorithm checks the unique superclass, and so on.

    • In C++, the method is still determined by the class of the receiver, but because a class can have multiple superclasses, the problem of deciding which method to invoke is more complicated.

    • In languages like Self, which have methods but no classes, the method is either found in a named slot on the receiver itself, or possibly is found in the prototype from which the object was cloned.

    • In more advanced object-oriented languages, the method-dispatch algorithm examines not only the receiver but the arguments that are passed along with the message. This idea is sometimes referred to as 'multimethods'. (To a degree, this technique can be simulated using what Smalltalk calls double dispatch, but there's a programming cost and a performance cost.) I believe the languages Cecil, Diesel, and Dylan all use some form of multimethod dispatch, but I'm teetering on the edge of my expertise.


It's hard to say without a context, but I'd describe it as the process which takes a method invocation in source code, decides which method requires executing, and executes it, performing any argument conversions, defaulting etc as required by the language.

The decision part of method dispatch may be purely at execution time (e.g. in a dynamic language), purely at compile time (e.g. calling a static method in C#/Java), or both (calling a virtual method in C#/Java).

Different languages can have significantly different approaches to method dispatch.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号