分派表(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。每一次呼叫虛擬方法時,就會透過分派表分派到實際對應的方法。
相關條目
參考資料
Wikiwand - on
Seamless Wikipedia browsing. On steroids.