用反射来改写简单工厂设计模式

     最近做了个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();
		}
	}
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值