一,命令模式把一个请求或操作封装到一个对象中,命令模式允许系统使用不同的请求把客户端参数化,对请求排 队或者记录请求日志,可以提供命令的撤消等操作
在命令模式的运用上,平时也没有怎么看到,查了些相应的资料,多以编辑器等操作命令进行操作最为实在...
调用者---命令---接收者
例子:
角色一,调用者
package com.wqy.command;
/**
* 键盘为命令触发者
*
* @author wu_quanyin(09817)
* @version 1.0
* @date 2010-7-17 下午04:04:22
*/
public class KeyBoardInvoker {
private OperateCommand operateCommand;
public KeyBoardInvoker(OperateCommand operateCommand){
this.operateCommand=operateCommand;
}
public void action(){
operateCommand.execute();
}
}
角色二,接收者
package com.wqy.command;
/**
* 笔记本为接收者执行命令
*
* @author wu_quanyin(09817)
* @version 1.0
* @date 2010-7-17 下午04:09:41
*/
public class NoteReceiver {
public void writer(){
System.out.println("正在进行写操作。。。");
}
public void undo(){
System.out.println("正在进行取消操作...");
}
}
角色三,命令
package com.wqy.command;
/**
* @author wu_quanyin(09817)
* @version 1.0
* @date 2010-7-17 上午08:30:56
*/
public interface OperateCommand {
public void execute();
}
package com.wqy.command;
/**
* @author wu_quanyin(09817)
* @version 1.0
* @date 2010-7-17 下午04:10:29
*/
public class UndoCommand implements OperateCommand {
private NoteReceiver receiver;
public UndoCommand(NoteReceiver receiver){
this.receiver=receiver;
}
@Override
public void execute() {
receiver.undo();
}
}
package com.wqy.command;
/**
* @author wu_quanyin(09817)
* @version 1.0
* @date 2010-7-17 下午04:10:29
*/
public class WriteCommand implements OperateCommand {
private NoteReceiver receiver;
public WriteCommand(NoteReceiver receiver){
this.receiver=receiver;
}
@Override
public void execute() {
receiver.writer();
}
}
测试
package com.wqy.command;
/**
* @author wu_quanyin(09817)
* @version 1.0
* @date 2010-7-17 下午04:26:14
*/
public class Client {
public static void main(String[] args) {
NoteReceiver note=new NoteReceiver();
OperateCommand writeCommand=new WriteCommand(note);
KeyBoardInvoker keyBoard1=new KeyBoardInvoker(writeCommand);
keyBoard1.action();
System.out.println("-----------------------------");
OperateCommand undoCommand=new UndoCommand(note);
KeyBoardInvoker keyBoard2=new KeyBoardInvoker(undoCommand);
keyBoard2.action();
}
}
打印出:
正在进行写操作。。。
-------------------------------------
正在进行取消操作...