WEB开发网
开发学院软件开发Java hand first 设计模式 - 命令模式 阅读

hand first 设计模式 - 命令模式

 2009-09-17 00:00:00 来源:WEB开发网   
核心提示: 关电视 Java代码publicclassTVOffCommandimplementsCommand{privateTVtv;publicTVOffCommand(TVtv){this.tv=tv;}@Overridepublicvoidexecute(){//TODOAuto-generate

关电视

Java代码   

public class TVOffCommand implements Command { 
 
 private TV tv; 
 
 public TVOffCommand(TV tv) { 
 this.tv = tv; 
 } 
 
 @Override 
 public void execute() { 
 // TODO Auto-generated method stub 
 tv.off(); 
 
 } 
 
 @Override 
 public void undo() { 
 // TODO Auto-generated method stub 
 tv.on(); 
 
 } 
 
}

空命令

Java代码   

public class NoCommand implements Command { 
 
 @Override 
 public void execute() { 
 // TODO Auto-generated method stub 
 
 } 
 
 @Override 
 public void undo() { 
 // TODO Auto-generated method stub 
 
 } 
 
}

摇控器

Java代码   

public class Controler { 
 //有7个电器设置控制接口 
     private final static int PROTNUM = 7; 
 //开控制命令组 
     private Command[] onCommands = new Command[PROTNUM]; 
 //关控制命令组 
     private Command[] offCommands = new Command[PROTNUM]; 
 
 private Command noCommand = new NoCommand(); 
 //一个用于撤消的List 
 private static LinkedList<Command> undoList = new LinkedList<Command>(); 
 
 public Controler() { 
  //初始化所有命令组有空命令 
          for (int i = 0; i < PROTNUM; i++) { 
  onCommands[i] = noCommand; 
  offCommands[i] = noCommand; 
 } 
 } 
 
 
//根据接口号设置开关命令 
public void setProt(int index,Command onCommand,Command offCommand){ 
 if(index>PROTNUM) 
  return; 
 onCommands[index] = onCommand; 
 offCommands[index] = offCommand; 
 } 
 
 
//根据接口号执行开命令 
public void onButton(int index){ 
 onCommands[index].execute(); 
 //增加到撤消的List 
         undoList.add(onCommands[index]); 
 } 
 
//根据接口号执行关命令 
public void offBuffon(int index){ 
 offCommands[index].execute(); 
          //增加到撤消的List 
 undoList.add(offCommands[index]); 
 } 
 
//撤消操作 
public void undoButton(){ 
 //取撤消的List的最后一个命令进行撤消 
         Command command = undoList.removeLast(); 
 command.undo(); 
 } 
 
}

上一页  1 2 3 4 5  下一页

Tags:hand first 设计模式

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接