分派表
外观
分派表(dispatch table)是存储函数(或方法)指针(或地址)的表格[1]。若要在面向对象程式设计实现后期绑定,分派表是常见的作法。
Perl语言的实现
[编辑]以下程序说明一种在Perl语言中实现分派表的方式,用关联数组(hash)存储对应程序的位置(也称为函数指针)。
# Define the table using one anonymous code-ref and one named code-ref
my %dispatch = (
"-h" => sub { return "hello\n"; },
"-g" => \&say_goodbye
);
sub say_goodbye {
return "goodbye\n";
}
# Fetch the code ref from the table, and invoke it
my $sub = $dispatch{$ARGV[0]};
print $sub ? $sub->() : "unknown argument\n";
用perl greet -h
执行此程序会回应"hello",若用perl greet -g
执行此程序则会回应"goodbye"。
JavaScript里的实现
[编辑]以下是用JavaScript实现分派表:
const thingsWeCanDo = {
doThisThing() { /* behavior */ },
doThatThing() { /* behavior */ },
doThisOtherThing() { /* behavior */ },
default() { /* behavior */ }
};
function doSomething(doWhat) {
const thingToDo = Object.hasOwn(thingsWeCanDo, doWhat)
? doWhat
: "default";
return thingsWeCanDo[thingToDo]();
}
虚拟方法表
[编辑]在支持虚拟方法的面向对象编程语言中,编译器会自动的为有虚拟方法的类的物件产生分派表。此表称为虚拟方法表,简称vtable。每一次调用虚拟方法时,就会透过分派表分派到实际对应的方法。
相关条目
[编辑]参考资料
[编辑]- ^ Goldfuss, Alice. Function Dispatch Tables in C. alicegoldfuss.com. [23 January 2021].
- Diomidis Spinellis (2003). Code Reading: The Open Source Perspective. Boston, MA: Addison-Wesley. ISBN 0-201-79940-5