备忘录:在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。
通俗的讲就像课本举得例子:一般玩单机游戏都会有存档这个选项,这就可以利用备忘录模式来实现;一些撤销,悔棋操作,都是回到之前的状态。
下面来说一下象棋中的悔棋操作如何利用备忘录模式来实现。
package 象棋悔棋操作;
public class GameRole {
private String name;
private int x;
private int y;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public void StateDisplay() {
System.out.println("这颗棋子的信息:"+this.name+"("+this.x+","+this.y+")");
}
public void GetInitState() {
this.name="马";
this.x=2;
this.y=1;
}
public void Run1() {
this.name="马";
this.x=1;
this.y=2;
}
public void Run2() {
this.name="马";
this.x=3;
this.y=2;
}
public void Run3() {
this.name="马";
this.x=4;
this.y=1;
}
public RoleStateMemento SaveState() {
return (new RoleStateMemento(name,x,y));
}
public void RecoveryState(RoleStateMemento memento) {
this.name=memento.getName();
this.x=memento.getX();
this.y=memento.getY();
}
}
package 象棋悔棋操作;
public class RoleStateMemento {
private String name;
private int x;
private int y;
public RoleStateMemento(String name, int x, int y) {
super();
this.name = name;
this.x = x;
this.y = y;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
package 象棋悔棋操作;
public class RoleStateCaretaker {
private RoleStateMemento memento;
public RoleStateMemento getMemento() {
return memento;
}
public void setMemento(RoleStateMemento memento) {
this.memento = memento;
}
}
package 象棋悔棋操作;
public class Test {
public static void main(String[] args) {
System.out.println("开始时棋子的位置:");
GameRole a1=new GameRole();
a1.GetInitState();
a1.StateDisplay();
RoleStateCaretaker stateAdmin=new RoleStateCaretaker();
stateAdmin.setMemento(a1.SaveState());
System.out.println("移动后棋子的位置:");
a1.Run1();
a1.StateDisplay();
System.out.println("悔棋后棋子的位置:");
a1.RecoveryState(stateAdmin.getMemento());
a1.StateDisplay();
// TODO Auto-generated method stub
}
}
运行结果:
uml图: