一连串命令执行后,可以回退
public interface Command {
/**
* 执行
* @param s
*/
void write(String s);
/**
* 回退
*/
void back();
}
public class Content {
public String msg = "";
}
public class WriteCmd implements Command{
Content content;
String s;
public WriteCmd(Content content) {
this.content = content;
}
@Override
public void write(String s) {
this.s = s;
content.msg += s;
}
@Override
public void back() {
content.msg = content.msg.substring(0, content.msg.length() - s.length());
}
}
public class CmdManager {
// 利用栈现进后出的特性存放命令
static Stack<Command> commands = new Stack<>();
public static void add(Command cmd){
commands.push(cmd);
}
public static void back(){
if (!commands.isEmpty()){
Command cmd = commands.pop();
cmd.back();
}
}
}
public class Test {
public static void main(String[] args) {
Content content = new Content();
WriteCmd cmd1 = new WriteCmd(content);
cmd1.write("我");
System.out.println(content.msg);
CmdManager.add(cmd1);
WriteCmd cmd2 = new WriteCmd(content);
cmd2.write("爱");
System.out.println(content.msg);
CmdManager.add(cmd2);
WriteCmd cmd3 = new WriteCmd(content);
cmd3.write("祖国");
System.out.println(content.msg);
CmdManager.add(cmd3);
System.out.println(" -------------- 开始回退 --------------");
CmdManager.back();
System.out.println(content.msg);
CmdManager.back();
System.out.println(content.msg);
CmdManager.back();
System.out.println(content.msg);
CmdManager.back();
System.out.println(content.msg);
}
}
执行结果:
我
我爱
我爱祖国
-------------- 开始回退 --------------
我爱
我
来源:oschina
链接:https://my.oschina.net/icefoxhz/blog/4952319