定义:是一种数据驱动的设计模式。请求以命令的形式包裹在对象中,并传给调用对象。调用对象寻找可以处理该命令的合适的对象,并把该命令传给相应的对象,该对象执行命令。
个人理解:最常用对这个模式的理解就是撤销,比如csdn写了一段话不小心删除了,按Ctrl+Z就可以撤销,还原操作。
UML图解:
优点:新的命令容易添加
缺点:(选自菜鸟编程)使用命令模式可能会导致某些系统有过多的具体命令类。
代码:
//抽象类及对应的抽象方法
public abstract class Command {
public abstract void doit(); //exec run
public abstract void undo();
}
//要操作的内容
public class Content {
String msg = "hello everybody ";
}
//要执行的操作
//复制
public class CopyCommand extends Command {
Content c;
public CopyCommand(Content c) {
this.c = c;
}
@Override
public void doit() {
c.msg = c.msg + c.msg;
}
@Override
public void undo() {
c.msg = c.msg.substring(0, c.msg.length()/2);
}
}
//删除
public class DeleteCommand extends Command {
Content c;
String deleted;
public DeleteCommand(Content c) {
this.c = c;
}
@Override
public void doit() {
deleted = c.msg.substring(0, 5);
c.msg = c.msg.substring(5, c.msg.length());
}
@Override
public void undo() {
c.msg = deleted + c.msg;
}
}
//插入
public class InsertCommand extends Command {
Content c;
String strToInsert = "http://www.csdn.com";
public InsertCommand(Content c) {
this.c = c;
}
@Override
public void doit() {
c.msg = c.msg + strToInsert;
}
@Override
public void undo() {
c.msg = c.msg.substring(0, c.msg.length()-strToInsert.length());
}
}
//调用
public class Main {
public static void main(String[] args) {
Content c = new Content();
Command insertCommand = new InsertCommand(c);
insertCommand.doit();
insertCommand.undo();
Command copyCommand = new CopyCommand(c);
insertCommand.doit();
insertCommand.undo();
Command deleteCommand = new DeleteCommand(c);
deleteCommand.doit();
deleteCommand.undo();
//可以变成一条链
List<Command> commands = new ArrayList<>();
commands.add(new InsertCommand(c));
commands.add(new CopyCommand(c));
commands.add(new DeleteCommand(c));
for(Command comm : commands) {
comm.doit();
}
System.out.println(c.msg);
//类似于撤回多个步骤
for(int i= commands.size()-1; i>=0; i--) {
commands.get(i).undo();
}
System.out.println(c.msg);
}
总结:认为是命令的地方都可以使用命令模式,比如:GUI 中每一个按钮都是一条命令。