属于行为型模式(共11种)

    目的:
    结合 chain of responsibility 可以实现 undo的功能 (就是撤销ctrl+z)

    类图:
    image.png

    部分代码实现

    1. public abstract class Command {
    2. public abstract void doit(); //exec run
    3. public abstract void undo();
    4. }
    5. ---------------------------------------------------------
    6. public class CopyCommand extends Command {
    7. Content c;
    8. public CopyCommand(Content c) {
    9. this.c = c;
    10. }
    11. @Override
    12. public void doit() {
    13. c.msg = c.msg + c.msg;
    14. }
    15. @Override
    16. public void undo() {
    17. c.msg = c.msg.substring(0, c.msg.length()/2);
    18. }
    19. }
    20. ---------------------------------------------------------
    21. public class DeleteCommand extends Command {
    22. Content c;
    23. String deleted;
    24. public DeleteCommand(Content c) {
    25. this.c = c;
    26. }
    27. @Override
    28. public void doit() {
    29. deleted = c.msg.substring(0, 5);
    30. c.msg = c.msg.substring(5, c.msg.length());
    31. }
    32. @Override
    33. public void undo() {
    34. c.msg = deleted + c.msg;
    35. }
    36. }
    37. ---------------------------------------------------------
    38. public class Main {
    39. public static void main(String[] args) {
    40. Content c = new Content();
    41. Command insertCommand = new InsertCommand(c);
    42. insertCommand.doit();
    43. insertCommand.undo();
    44. Command copyCommand = new CopyCommand(c);
    45. insertCommand.doit();
    46. insertCommand.undo();
    47. Command deleteCommand = new DeleteCommand(c);
    48. deleteCommand.doit();
    49. deleteCommand.undo();
    50. List<Command> commands = new ArrayList<>();
    51. commands.add(new InsertCommand(c));
    52. commands.add(new CopyCommand(c));
    53. commands.add(new DeleteCommand(c));
    54. for(Command comm : commands) {
    55. comm.doit();
    56. }
    57. System.out.println(c.msg);
    58. for(int i= commands.size()-1; i>=0; i--) {
    59. commands.get(i).undo();
    60. }
    61. System.out.println(c.msg);
    62. }
    63. }

    command + memento 实现 transaction事务回滚
    command + composite 实现 宏命令 多种命令组合