分派表
外观
分派表(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