实现一个由 dfa 简单明了地演示的接口是干净和优雅的(并且是“官方”支持的方式)。这就是接口概念的意义所在。
在 C# 中,我们可以为喜欢在 c 中使用函数指针的程序员使用委托,但 DFA 的技术是使用方式。
你也可以有一个数组
Command[] commands =
{
new CommandA(), new CommandB(), new CommandC(), ...
}
然后你可以按索引执行命令
commands[7].exec();
抄袭 DFA,但有一个抽象基类而不是接口。请注意稍后将使用的 cmdKey。根据经验,我意识到设备命令通常也有子命令。
abstract public class Command()
{
abstract public byte exec(String subCmd);
public String cmdKey;
public String subCmd;
}
因此构建你的命令,
public class CommandA
extends Command
{
public CommandA(String subCmd)
{
this.cmdKey = "A";
this.subCmd = subCmd;
}
public byte exec()
{
sendWhatever(...);
byte status = receiveWhatever(...);
return status;
}
}
然后,您可以通过提供键值对吸吮函数来扩展通用 HashMap 或 HashTable:
public class CommandHash<String, Command>
extends HashMap<String, Command>
(
public CommandHash<String, Command>(Command[] commands)
{
this.commandSucker(Command[] commands);
}
public commandSucker(Command[] commands)
{
for(Command cmd : commands)
{
this.put(cmd.cmdKey, cmd);
}
}
}
然后构建你的命令存储:
CommandHash commands =
new CommandHash(
{
new CommandA("asdf"),
new CommandA("qwerty"),
new CommandB(null),
new CommandC("hello dolly"),
...
});
现在您可以客观地发送控制
commands.get("A").exec();
commands.get(condition).exec();