简介:
简略来说,就像咱们的复制、删除、插入等等都是命令,咱们将命令封装为一个对象,并且反对撤销,将一系列命令串成一条链或者与链表联合应用,能够实现一系列的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); }}
测试后果: