在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态.这样以后就可以将该对象恢复到原先保存的状态.
快照模式和clone方式的区别在于此模式可以有选择性的保存.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| package memento;
public class RoleStateMemento { private int vitality;
public RoleStateMemento(int vitality) { this.vitality = vitality; }
public int getVitality() { return vitality; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| package memento;
public class GameRole { private int vitality; private int attack;
public RoleStateMemento saveState() { return new RoleStateMemento(vitality); }
public void recoveryState(RoleStateMemento memento) { if (memento == null) return; vitality = memento.getVitality(); }
public int getVitality() { return vitality; }
public void setVitality(int vitality) { this.vitality = vitality; }
public int getAttack() { return attack; }
public void setAttack(int attack) { this.attack = attack; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| package memento;
import java.util.Stack;
public class Caretaker { private Stack<RoleStateMemento> mementos;
public Caretaker() { mementos = new Stack<RoleStateMemento>(); }
public void push(RoleStateMemento memento) { mementos.push(memento); }
public RoleStateMemento get() { return mementos.pop(); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| package memento;
public class Main { public static void main(String[] args) { Caretaker caretaker = new Caretaker(); GameRole role = new GameRole(); role.setVitality(10); RoleStateMemento memento = role.saveState(); caretaker.push(memento);
role.setVitality(5); memento = role.saveState(); caretaker.push(memento); role.recoveryState(caretaker.get()); System.out.println(role.getVitality());
role.recoveryState(caretaker.get()); System.out.println(role.getVitality()); } }
|