あなたが探していると私が信じているものは、一般的に文献ではCommand Patternと呼ばれています。オブジェクト指向の多い言語では、通常、このパターンには、単一のメソッドを持つ共通のシンプルなCommandインターフェイスを実装する一連のクラスの作成が含まれます。execute()
ただし、D ではデリゲートがあり、おそらくこの目的のために数百もの小さなクラスを生成することを避けることができます。
ラムダ式 ( http://dlang.org/expression.html#Lambda )を使用した D の代替案の 1 つを次に示します。
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. :)