框架得这样学
:lol: 大家都在学习各种各样的框架. 但学到什么样才算个头,掌握的程序是个什么样:了解,熟悉,精通?
过去发问过"如何重构STRUTS的ACTION" 当时只知道有个action类,不知道有个DISPATCHACTION. 为了减少类的数量,回到面向过程的思路上去了,根据参数通过if else的判断,处理相应的操作. 对于替代IF ELSE传统思想的面向对象方法很多,策略模式,状态模式,命令模式..都能解决这样的问题,问题在于你的业务是什么样的.
现在又看到了问题:
[code=java] public interface command{ public String execute(); }[/code]
如果每一个命令都要实现以上接口的话,那文件太多了,我想把相关的命令都放在一个文件中,比如有关用户的命令,把所有要实现的命令就放在用户相关的操作文件中,请问下老师该怎么设计啊?
根据上面的问题,可以通过动态代理+反射方法实现 像下面的方法:
public class TestReflectCommand {
public static void main(String args){
CommandLoader cl=new DefaultCommandLoader(new DefaultShowCommand()); cl.excute("executeShowList",null); } }
public interface CommandLoader {
void excute(String commandName,Object argument); }
public class DefaultCommandLoader implements CommandLoader {
private ShowCommand showCommand;
private HashMap subCommandMap=new HashMap();
public DefaultCommandLoader(ShowCommand showCommand){ this.showCommand=showCommand; init(); }
private void init() {
Method allMethod=this.showCommand.getClass().getMethods(); for(int i=0;i<allMethod.length;i++){ Method m=allMethod; if(m.getName().startsWith("execute")){ subCommandMap.put(m.getName(), m); } } }
public void excute(String commandName, Object argument) {
Method m=(Method) this.subCommandMap.get(commandName);
if(m==null){ throw new NullPointerException("not found command"); } try{ m.invoke(this.showCommand,argument); } catch(Exception e){ throw new RuntimeException("Load command
这个方法是从SPRING的思想来的.
当然STRUTS里也有这样的思想....
所以学框架还得多看看她的源码....