标签:
定义:将“请求”封装成对象,以便使用不同的请求、队列或者日志来参数化其他对象。命令模式也支持可撤销的操作。
UML图:
1 //定义命令接口 2 public interface Command { 3 4 public void execute(); 5 6 public void undo(); 7 8 } 9 //动作接收者 10 public class Receiver { 11 12 public void open(){ 13 System.out.println("receiver open"); 14 } 15 16 public void close(){ 17 System.out.println("receiver close"); 18 } 19 } 20 21 //实现命令接口 22 public class ConcreteCommand implements Command{ 23 24 private Receiver mRec = null; 25 public ConcreteCommand(Receiver rec) { 26 // TODO Auto-generated constructor stub 27 mRec = rec; 28 } 29 @Override 30 public void execute() { 31 // TODO Auto-generated method stub 32 mRec.open(); 33 } 34 35 @Override 36 public void undo() { 37 // TODO Auto-generated method stub 38 mRec.close(); 39 } 40 41 } 42 //调用者 43 public class Invoker { 44 45 Command mCommand = null; 46 47 public void setCommand(Command com){ 48 mCommand = com; 49 } 50 51 public void execute(){ 52 if(mCommand != null){ 53 mCommand.execute(); 54 } 55 } 56 57 public void undo(){ 58 if(mCommand != null){ 59 mCommand.undo(); 60 } 61 } 62 } 63 //客户端 64 public class Client { 65 66 public static void main(String[] args) { 67 Invoker invoker = new Invoker(); 68 Receiver rec = new Receiver(); 69 ConcreteCommand concreteCommand = new ConcreteCommand(rec); 70 invoker.setCommand(concreteCommand); 71 invoker.execute(); 72 invoker.undo(); 73 } 74 }
标签:
原文地址:http://www.cnblogs.com/jaden/p/4401530.html