我相信你正在尋找的東西通常在文獻中稱爲Command Pattern。在大量的OO語言中,這種模式通常涉及創建一堆類,這些類實現了一個通用的簡單的接口,該接口具有單個方法。 然而,在D中,您有代表,並且可能避免爲此目的生成潛在的100個小類。
這裏是可能的d備選之一,使用lambda表達式(http://dlang.org/expression.html#Lambda):
module command2;
import std.stdio;
import std.conv;
import std.array;
// 2 = binary operation
alias int delegate(int arg1, int arg2) Command2;
// Global AA to hold all commands
Command2[string] commands;
// WARNING: assumes perfect string as input!!
void execute(string arg) {
auto pieces = split(arg);
int first = to!int(pieces[1]);
int second = to!int(pieces[2]);
Command2 cmd = commands[pieces[0]];
int result = cmd(first, second); // notice we do not need a big switch here
writeln(arg, " --> ", result);
} // execute() function
void main(string[] args) {
commands["add"] = (int a, int b) => a + b;
commands["sub"] = (int a, int b) => a - b;
commands["sqrt"] = (int a, int b) => a * a; // second parameter ignored
// ... add more commands (or better call them operations) here...
execute("add 2 2");
execute("sqrt 4 0"); // had to have 0 here because execute assumes perfect imput
} // main() function
這裏是源代碼叉和玩耍:http://dpaste.dzfl.pl/41d72036
我將寫入OO版本時我發現更多的時間...
關於在某個目錄中執行腳本/應用程序......這僅僅是編寫一個函數,它需要參數,並調用std.process.execute()
。一個非常快速的例子,如何擴展上面的代碼:
// WARNING: no error checking, etc!
int factoriel(int arg, int ignored) {
auto p = std.process.execute(["./funcs/factoriel", to!string(arg)]);
return to!int(p.output);
} // factoriel() function
...
// in main()
commands["fact"] = toDelegate(&factoriel);
...
execute("fact 6 0"); // again, we add 0 because we do not know how to do unary operations, yet. :)
不錯,你也使用std.traits函數而不是__traits像我一樣。 –