java设计模式之Active Object

ActiveObject模式是Command模式的一种,是实现多线程控制的一项古老技术.
在《敏捷软件开发》这本书中描述的算法如下:
1、构造一个命令。(实现Command模式的一个命令)
2、将该命令放入Active ObjectEngine(也就是放入一个队列,LinkedList)
3、从该Engine取出一个命令,执行,若该命令没有执行过,设为执行过,然后将自己加入队列尾部,若执行过,判断该命令执行需要的事件发生没有,未发生,再将自己加入队列尾部。事件发生了,将需要执行的命令加入队列尾部。
 
具体代码如下:
 
//典型的Command模式,需要有一个接口.接口中有一个统一的方法,这就是"将命令/请求封装为对象",没有大多数类的方法和变量
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));
 }
 
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值