优点
- 提供了一种恢复机制
- 实现了信息的封装
缺点
- 每次创建备忘录对象都会消耗内存
public class Memento {
private String stoneProtection;
private int holeNumber;
private int holeLevel;
public Memento(String stoneProtection, int holeNumber, int holeLevel) {
this.stoneProtection = stoneProtection;
this.holeNumber = holeNumber;
this.holeLevel = holeLevel;
}
public String getStoneProtection() {
return stoneProtection;
}
public void setStoneProtection(String stoneProtection) {
this.stoneProtection = stoneProtection;
}
public int getHoleNumber() {
return holeNumber;
}
public void setHoleNumber(int holeNumber) {
this.holeNumber = holeNumber;
}
public int getHoleLevel() {
return holeLevel;
}
public void setHoleLevel(int holeLevel) {
this.holeLevel = holeLevel;
}
@Override
public String toString() {
return "Memento{" +
"stoneProtection='" + stoneProtection + '\'' +
", holeNumber=" + holeNumber +
", holeLevel=" + holeLevel +
'}';
}
public class CareTaker {
private List<Memento> mementoList;
public CareTaker() {
this.mementoList = new ArrayList<>();
}
public void addMemento(Memento memento){
mementoList.add(memento);
}
public Memento getMemento(int index){
return mementoList.get(index);
}
}
/**
* 角色(Originator)
*/
public class MonsterHunter {
private String stoneProtection;
private int holeNumber;
private int holeLevel;
public String getStoneProtection() {
return stoneProtection;
}
public void setStoneProtection(String stoneProtection) {
this.stoneProtection = stoneProtection;
}
public int getHoleNumber() {
return holeNumber;
}
public void setHoleNumber(int holeNumber) {
this.holeNumber = holeNumber;
}
public int getHoleLevel() {
return holeLevel;
}
public void setHoleLevel(int holeLevel) {
this.holeLevel = holeLevel;
}
public Memento createMemento(){
return new Memento(this.stoneProtection, this.holeNumber, this.holeLevel);
}
public void restoreMemento(Memento memento){
this.setStoneProtection(memento.getStoneProtection());
this.setHoleNumber(memento.getHoleNumber());
this.setHoleLevel(memento.getHoleLevel());
}
@Override
public String toString() {
return "MonsterHunter{" +
"stoneProtection='" + stoneProtection + '\'' +
", holeNumber=" + holeNumber +
", holeLevel=" + holeLevel +
'}';
}
}
测试类
public class Test {
public static void main(String[] args) {
MonsterHunter monsterHunter = new MonsterHunter();
monsterHunter.setStoneProtection("天佑护石");
monsterHunter.setHoleNumber(3);
monsterHunter.setHoleLevel(4);
System.out.println("===============初始状态===============");
System.out.println(monsterHunter.toString());
CareTaker careTaker = new CareTaker();
careTaker.addMemento(monsterHunter.createMemento());
monsterHunter.setStoneProtection("垃圾");
monsterHunter.setHoleNumber(1);
monsterHunter.setHoleLevel(1);
System.out.println("===============错误状态===============");
System.out.println(monsterHunter.toString());
monsterHunter.restoreMemento(careTaker.getMemento(0));
System.out.println("===============回档状态===============");
System.out.println(monsterHunter.toString());
}
}
结果