备忘录模式
恢复之前状态
1.一个游戏,里面有个创建备忘录的方法,该方法存储当前游戏进度到备忘录中,并且返回备忘录.另外一个是拿到备忘录,将备忘录的数据恢复到游戏中.
public class Game {
int gamelv;
String name;
String age;
String password;
public Game(int gamelv, String name, String age) {
this.gamelv = gamelv;
this.name = name;
this.age = age;
}
public Game() {
}
public Memento createMemento() {
return new Memento(this.gamelv,this.name,this.age);
}
public void restoreMemento(Memento memento) {
this.gamelv = memento.gamelv;
this.name = memento.name;
this.age = memento.age;
}
public int getGamelv() {
return gamelv;
}
public void setGamelv(int gamelv) {
this.gamelv = gamelv;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
2.备忘录的类
public class Memento {
int gamelv;
String name;
String age;
public Memento(int gamelv, String name, String age) {
this.gamelv = gamelv;
this.name = name;
this.age = age;
}
public int getGamelv() {
return gamelv;
}
public void setGamelv(int gamelv) {
this.gamelv = gamelv;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
3.备忘录管理者 ,一个是获取当前管理者手里的备忘录,另外一个是将游戏创建的备忘录保存到管理者手中.
public class Caretaker {
//备忘录对象
private Memento memento;
public Memento getMemento() {
return memento;
}
public void setMemento(Memento memento) {
this.memento = memento;
}
}
4.测试
public class Test {
public void test() {
Game game = new Game();
game.setAge("11");
Caretaker caretaker = new Caretaker(); //备忘录管理者
caretaker.setMemento(game.createMemento()); //保存Game状态
game.setGamelv(22); //改变game状态
game.restoreMemento(caretaker.getMemento()); //恢复game状态
}
}