markdown multiple dispatch(多重指派)与函数重载的关系
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown multiple dispatch(多重指派)与函数重载的关系相关的知识,希望对你有一定的参考价值。
## multiple dispatch与method overloading的关系
- multiple dispatch是在runtime根据参数类型决定要调用的方法的技术
- method overloading是在compile time根据参数类型决定要调用的方法.
对于静态语言而言, 可以通过模拟实现multiple dispatch. 对于动态语言而言, 实际上两者基本上是同义词. 但并不是说动态语言天生支持multiple dispatch, 静态语言就不支持multiple dispatch.
## Python中的multiple dispatch
Python原生是不支持multiple dispatch的, 可以通过第三方库来模拟:
```python
from multimethods import Dispatch
from game_objects import Asteroid, Spaceship
from game_behaviors import ASFunc, SSFunc, SAFunc
collide = Dispatch()
collide.add_rule((Asteroid, Spaceship), ASFunc)
collide.add_rule((Spaceship, Spaceship), SSFunc)
collide.add_rule((Spaceship, Asteroid), SAFunc)
def AAFunc(a, b):
"""Behavior when asteroid hits asteroid"""
# ...define new behavior...
collide.add_rule((Asteroid, Asteroid), AAFunc)
# ...later...
collide(thing1, thing2)
```
## Java中的multiple dispatch
```java
interface Collideable {
void collideWith(final Collideable other);
/* These methods would need different names in a language without method overloading. */
void collideWith(final Asteroid asteroid);
void collideWith(final Spaceship spaceship);
}
class Asteroid implements Collideable {
public void collideWith(final Collideable other) {
// Call collideWith(Asteroid) on the other object.
other.collideWith(this);
}
public void collideWith(final Asteroid asteroid) {
// Handle Asteroid-Asteroid collision.
}
public void collideWith(final Spaceship spaceship) {
// Handle Asteroid-Spaceship collision.
}
}
class Spaceship implements Collideable {
public void collideWith(final Collideable other) {
// Call collideWith(Spaceship) on the other object.
other.collideWith(this);
}
public void collideWith(final Asteroid asteroid) {
// Handle Spaceship-Asteroid collision.
}
public void collideWith(final Spaceship spaceship) {
// Handle Spaceship-Spaceship collision.
}
}
```
## 参考链接
- [Multiple Dispatch](https://en.wikipedia.org/wiki/Multiple_dispatch)
- [Multiple Dispatch vs. Function Overloading](https://softwareengineering.stackexchange.com/questions/125084/multiple-dispatch-vs-function-overloading)
以上是关于markdown multiple dispatch(多重指派)与函数重载的关系的主要内容,如果未能解决你的问题,请参考以下文章
markdown multiple-row-dotted-line.md
Django admin,使用ImportExportModelAdmin和MarkdownxModelAdmin(Multiple)
HTML5基础 input file multiple 上传多个文件
电脑终止代码MULTIPLE
easyui的组合树怎么设置multiple
view UI 里面日期选择器多选 multiple 不生效