GOF

↘锁芯ラ 提交于 2021-02-11 14:00:55

一连串命令执行后,可以回退

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);
    }
}

执行结果:

我爱

我爱祖国

-------------- 开始回退 --------------

我爱

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!