撤销功能的实现——备忘录模式(三)

21.3 完整解决方案

为了实现撤销功能,Sunny公司开发人员决定使用备忘录模式来设计中国象棋软件,其基本结构如图21-4所示:

撤销功能的实现——备忘录模式(三) - 图1

在图21-4中,Chessman充当原发器,ChessmanMemento充当备忘录,MementoCaretaker充当负责人,在MementoCaretaker中定义了一个ChessmanMemento类型的对象,用于存储备忘录。完整代码如下所示:

  1. //象棋棋子类:原发器
  2. class Chessman {
  3. private String label;
  4. private int x;
  5. private int y;
  6. public Chessman(String label,int x,int y) {
  7. this.label = label;
  8. this.x = x;
  9. this.y = y;
  10. }
  11. public void setLabel(String label) {
  12. this.label = label;
  13. }
  14. public void setX(int x) {
  15. this.x = x;
  16. }
  17. public void setY(int y) {
  18. this.y = y;
  19. }
  20. public String getLabel() {
  21. return (this.label);
  22. }
  23. public int getX() {
  24. return (this.x);
  25. }
  26. public int getY() {
  27. return (this.y);
  28. }
  29. //保存状态
  30. public ChessmanMemento save() {
  31. return new ChessmanMemento(this.label,this.x,this.y);
  32. }
  33. //恢复状态
  34. public void restore(ChessmanMemento memento) {
  35. this.label = memento.getLabel();
  36. this.x = memento.getX();
  37. this.y = memento.getY();
  38. }
  39. }
  40. //象棋棋子备忘录类:备忘录
  41. class ChessmanMemento {
  42. private String label;
  43. private int x;
  44. private int y;
  45. public ChessmanMemento(String label,int x,int y) {
  46. this.label = label;
  47. this.x = x;
  48. this.y = y;
  49. }
  50. public void setLabel(String label) {
  51. this.label = label;
  52. }
  53. public void setX(int x) {
  54. this.x = x;
  55. }
  56. public void setY(int y) {
  57. this.y = y;
  58. }
  59. public String getLabel() {
  60. return (this.label);
  61. }
  62. public int getX() {
  63. return (this.x);
  64. }
  65. public int getY() {
  66. return (this.y);
  67. }
  68. }
  69. //象棋棋子备忘录管理类:负责人
  70. class MementoCaretaker {
  71. private ChessmanMemento memento;
  72. public ChessmanMemento getMemento() {
  73. return memento;
  74. }
  75. public void setMemento(ChessmanMemento memento) {
  76. this.memento = memento;
  77. }
  78. }
  79. 编写如下客户端测试代码:
  80. [java] view plain copy
  81. class Client {
  82. public static void main(String args[]) {
  83. MementoCaretaker mc = new MementoCaretaker();
  84. Chessman chess = new Chessman("车",1,1);
  85. display(chess);
  86. mc.setMemento(chess.save()); //保存状态
  87. chess.setY(4);
  88. display(chess);
  89. mc.setMemento(chess.save()); //保存状态
  90. display(chess);
  91. chess.setX(5);
  92. display(chess);
  93. System.out.println("******悔棋******");
  94. chess.restore(mc.getMemento()); //恢复状态
  95. display(chess);
  96. }
  97. public static void display(Chessman chess) {
  98. System.out.println("棋子" + chess.getLabel() + "当前位置为:" + "第" + chess.getX() + "行" + "第" + chess.getY() + "列。");
  99. }
  100. }

编译并运行程序,输出结果如下:

  1. 棋子车当前位置为:第1行第1列。
  2. 棋子车当前位置为:第1行第4列。
  3. 棋子车当前位置为:第1行第4列。
  4. 棋子车当前位置为:第5行第4列。
  5. ******悔棋******
  6. 棋子车当前位置为:第1行第4列。