最近做了个android 手机上的ftp服务器,由于ftp服务器要通过接收到的命令来做相应的处理,对于每一个ftp命令,我都要写一个相关的处理类。这样的话,当一个命令传过来之后,怎么实例化相应的命令类呢,最简单的方法就是用一个简单工厂设计模式了。不过这么多命令,我可不想对30命令用if else来处理,这样实在是太麻烦了。最后发现可以用java反射来做比较好。
public abstract class CommandManager implements Runnable {
protected static CommandMap[] cmdClasses = {
new CommandMap("USER", CommandUSER.class),
new CommandMap("PASS", CommandPASS.class),
new CommandMap("OPTS", CommandOPTS.class),
new CommandMap("PWD", CommandPWD.class),
new CommandMap("TYPE", CommandTYPE.class),
new CommandMap("SYST", CommandSYST.class),
new CommandMap("NOOP", CommandNOOP.class),
new CommandMap("CWD", CommandCWD.class),
new CommandMap("PORT", CommandPORT.class),
new CommandMap("PASV", CommandPASV.class),
new CommandMap("SIZE", CommandSIZE.class),
new CommandMap("LIST", CommandLIST.class),
new CommandMap("RETR", CommandRETR.class),
new CommandMap("NLST", CommandNLST.class),
new CommandMap("QUIT", CommandQUIT.class),
new CommandMap("NLST", CommandNLST.class),
new CommandMap("RMD", CommandRMD.class),
new CommandMap("STOR", CommandSTOR.class),
new CommandMap("DELE", CommandDELE.class),
new CommandMap("RNFR", CommandRNFR.class),
new CommandMap("XMKD", CommandMKD.class),
new CommandMap("RNTO", CommandRNTO.class),
new CommandMap("MKD", CommandMKD.class),
new CommandMap("FEAT", CommandFEAT.class),
new CommandMap("CDUP", CommandCDUP.class),
new CommandMap("XPWD", CommandPWD.class),
new CommandMap("APPE", CommandAPPE.class),
new CommandMap("XCUP", CommandCDUP.class),
new CommandMap("XRMD", CommandRMD.class) };
protected static void CreatCommand(String command,String para) {
CopyOfCommandManager cmdInstance = null;
for (int i = 0; i < cmdClasses.length; i++) {
if (cmdClasses[i].getName().equals(command)) {
Constructor<? extends CopyOfCommandManager> constructor;
try {
constructor = cmdClasses[i].getClass().getConstructor(
new Class[] { String.class });
} catch (NoSuchMethodException e) {
return;
}
try {
cmdInstance = constructor.newInstance(new Object[] {
para });
} catch (Exception e) {
return;
}
}
}
if (cmdInstance != null) {
cmdInstance.run();
}
}
}