我相信您正在寻找的东西在文献中通常称为Command Pattern。在重度 OO 语言中,这种模式通常涉及创建一堆类,这些类实现了一个通用的、简单的Command接口,该接口只有一个execute()
方法。然而,在 D 中,您有委托,并且可能可以避免为此目的生成潜在的数百个小类。
这是使用 lambda 表达式 ( http://dlang.org/expression.html#Lambda ) 的可能的 D 替代方案之一:
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
这是 fork 和玩的源代码: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. :)