public interface Command { public void execute() throws Exception; }
// 实现接口Command的具体不同命令/请求
public class SleepCommand implementsCommand{ private Command wakeupCommand = null; private ActiveObjectEngine engine = null; private long sleepTime = 0; private long startTime = 0; private boolean started = false; public SleepCommand(long milliseconds,ActiveObjectEngine e, CommandwakeupCommand){ sleepTime = milliseconds; engine = e; this.wakeupCommand =wakeupCommand; } public void execute() throws Exception{ long currentTime =System.currentTimeMillis(); if(!started){ started =true; startTime =currentTime; engine.addCommand(this); }else if((currentTime -startTime) < sleepTime){ engine.addCommand(this); }else{ engine.addCommand(wakeupCommand); } } }
//ActiveObjectEngine 对象维护了一个Command对象的链表.
public class ActiveObjectEngine { LinkedList itsCommands = new LinkedList(); public void addCommand(Command c){ itsCommands.add(c); } public void run() throws Exception{ while(!itsCommands.isEmpty()){ Command c =(Command) itsCommands.getFirst(); itsCommands.removeFirst(); c.execute(); } } }
//使用sleepCommand展示它的多线程行为.
public class DelayedTyperimplements Command{ private long itsDelay; private char itsChar; private static ActiveObjectEngine engine = newActiveObjectEngine(); private static boolean stop = false; public static void main(String[] args) throwsException{ engine.addCommand(newDelayedTyper(1000,'1')); engine.addCommand(newDelayedTyper(3000,'3')); engine.addCommand(newDelayedTyper(5000,'5')); engine.addCommand(newDelayedTyper(7000,'7')); Command stopCommand = newCommand(){ public voidexecute(){stop = true ;} }; engine.addCommand(newSleepCommand(20000,engine,stopCommand)); engine.run(); } public DelayedTyper(long delay,char c){ itsDelay = delay; itsChar = c; } public void execute()throws Exception{ System.out.print(itsChar); if(!stop){ delayAndRepeat(); } } public void delayAndRepeat() throwsCloneNotSupportedException{ engine.addCommand(newSleepCommand(itsDelay,engine,this)); } }