Commandのサンプル

あんまりコマンドじゃない。コマンド++

public class CommandSample {
    
    public static void main(String[] args) {
        StringBuilder buf = new StringBuilder();
        //          0123456789abc
        buf.append("Hello, world!");
        Sequence com = new Sequence(
            new Edit(0, 5, "こんにちは"),
            new Edit(12, 13, "???")
            );
        System.out.println(buf);
        Command undo = com.process(new CommandProcessor(buf));
        System.out.println(buf);
        Command redo = undo.process(new CommandProcessor(buf));
        System.out.println(buf);
        redo.process(new CommandProcessor(buf));
        System.out.println(buf);
    }
    interface Command {
        Command process(CommandProcessor proc);
    }
    static class Edit implements Command {
        int s; int e; String c;
        Edit(int s, int e, String c) { this.s = s; this.e = e; this.c = c; }
        public Command process(CommandProcessor proc) {
            return proc.exec(this);
        }
    }
    static class Sequence implements Command {
        Command[] cmds;
        Sequence(Command...cmds) { this.cmds = cmds; }
        public Command process(CommandProcessor proc) {
            return proc.exec(this);
        }
    }
    static class CommandProcessor {
        StringBuilder buf;
        CommandProcessor(StringBuilder buf) { this.buf = buf; }
        Command exec(Edit c) {
            String undo = buf.substring(c.s, c.e);
            buf.replace(c.s, c.e, c.c);
            return new Edit(c.s, c.s + c.c.length(), undo);
        }
        Command exec(Sequence c) {
            Command[] undos = new Command[c.cmds.length];
            for (int i = 0; i < c.cmds.length; i++) {
                Command undo = c.cmds[i].process(this);
                undos[undos.length - i - 1] = undo;
            }
            return new Sequence(undos);
        }
    }
}