简介:
简单来说,就像我们的复制、删除、插入等等都是命令,我们将命令封装为一个对象,并且支持撤销,将一系列命令串成一条链或者与链表结合使用,可以实现一系列的do和undo
模式类图:
command: 抽象的命令类
X_Command、Y_Command、Z_Command: 具体的命令
使用场景:
我现在能想到的一般是在画图软件,办公软件,开发工具(IDE)当中比较常见的,毕竟作为一个码农,复制粘贴用的多了:)
模式实例:
比如我对一串字符串进行一系列的操作,我这个例子可能不太准确,角色划分不太明显,参考:https://www.cnblogs.com/meet/p/5116430.html
https://blog.csdn.net/qq_22764659/article/details/81335701
1、Content被操作的对象
package com.mashibing.command;
public class Content {
String msg = "hello everybody ";;
}
2、Command抽象命令
package com.mashibing.command;
public abstract class Command {
public abstract void doit();
public abstract void undo();
}
3、InsertCommand插入命令:
package com.mashibing.command;
public class InsertCommand extends Command{
Content c;
String strToInsert="http://www.mashibing.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());
}
}
4、CopyCommand 复制命令
package com.mashibing.command;
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);
}
}
5、DeleteCommand删除命令
package com.mashibing.command;
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;
}
}
6、Main 测试
package com.mashibing.command;
import java.util.ArrayList;
import java.util.List;
/**
* command模式一般跟责任链模式结合,实现一连串的undo
* 也可以用双向链表的方式来做
*/
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);
copyCommand.doit();
copyCommand.undo();
Command deleteCommand = new DeleteCommand(c);
deleteCommand.doit();
deleteCommand.undo();
System.out.println(c.msg);
//串在一起一连串执行
List<Command> commands = new ArrayList<>();
commands.add(new InsertCommand(c));
commands.add(new CopyCommand(c));
commands.add(new DeleteCommand(c));
for(Command command : commands) {
command.doit();
}
System.out.println(c.msg);
//一连串撤回
for (int i = commands.size()-1; i >=0; i--){
commands.get(i).undo();
}
System.out.println(c.msg);
}
}
测试结果:
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。