命令模式,active object模式:
需要一个执行引擎,一个执行接口(规约),若干个实现类。
如 开关 后边接 电扇--》电扇开关
接电视:电视开关
空调:空调开关
开关(引擎并不知道要做什么),由后边的电器实现。也就意味着,电器要实现可开关接口。
可以实现多线程,通过控制条件如时间。RTC线程。通过返回非空对象实现do 和 undo。
public void execute();
public object do();
public object undo();
package advanceobject;
import java.util.LinkedList;
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();
}
}
}
package advanceobject;
public interface Command {
public void execute() throws Exception;
}
package advanceobject;
public class SleepCommand implements Command {
private Command wakeupCommand = null;
private ActiveObjectEngine engine=null;
private long sleepTime = 0;
private long startTime = 0;
private boolean started = false;
private String objectname=null;
private int count=0;
public SleepCommand(Command wakeupCommand, ActiveObjectEngine engine,
long sleepTime,String objname) {
super();
this.wakeupCommand = wakeupCommand;
this.engine = engine;
this.sleepTime = sleepTime;
this.objectname=objname;
}
@Override
public void execute() throws Exception {
// TODO Auto-generated method stub
long currentTime = System.currentTimeMillis();
if(!started){
System.out.println("Init control flag and ready to run");
started = true;
startTime=currentTime;
engine.addCommand(this);
}
else if((currentTime-startTime)<sleepTime){
System.out.println("Running do some business before condition is false "+objectname+" times "+count);
count++;
engine.addCommand(this);
}
else
{
System.out.println("Time out add exit into loop");
if(null!=wakeupCommand)
engine.addCommand(wakeupCommand);
}
}
}
package advanceobject;
public class TestMain {
public static void main(String[] args){
Command wakeup = null;
ActiveObjectEngine e=new ActiveObjectEngine();
SleepCommand c1=new SleepCommand(wakeup,e,10,"c1");
e.addCommand(c1);
SleepCommand c2=new SleepCommand(wakeup,e,10,"c2");
e.addCommand(c2);
SleepCommand c3=new SleepCommand(wakeup,e,10,"c3");
e.addCommand(c3);
SleepCommand c4=new SleepCommand(wakeup,e,10,"c4");
e.addCommand(c4);
try {
e.run();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}