class ReturnCommand implements Command{ PRivate final Object v; public Object execute(CommandContext ctxt){ return v; } ReturnCommand(Object v){this.v=v;} }
PrintCommand负责打印一句话 java代码:
class PrintCommand implements Command{ private final String msg; public Object execute(CommandContext ctxt){ ctxt.getLogger().log(msg); return null; } PrintCommand(String msg){this.msg=msg;} }
FailCommand负责报告错误
java代码:
class FailCommand implements Command{ private final String msg; public Object execute(CommandContext ctxt){ throw new CommandException(msg); } FailCommand (String msg){this.msg=msg;} }
如此等等。这样的基本元件还有很多,比如file copy, javac, zip, jar等。
但是,假如仅仅如此,那么这个工具的能力最多也就和ant一样。
我们最需要的,是把不同的command组合起来的能力。
而组合,最常见的,就是顺序执行。
java代码:
class SeqCommand implements Command{ private final Command c1; private final Command c2; public Object execute(CommandContext ctxt){ c1.execute(ctxt); return c2.execute(ctxt); } SeqCommand (Command c1, Command c2){ this.c1 = c1; this.c2 = c2; } }
new BoundCommand( new GetTimeCommand(), new CommandBinder(){ public Command bind(Object v){ final Command c2 = new PrintCommand("build time is "+v); final Command javacc = new JavaCCommand(); final Command done = new PrintCommand("build sUCcessful"); return new SeqCommand(c2, new SeqCommand(javacc, done)); } } );