设计模式-备忘录模式
基本介绍
- 备忘录模式(Memento Pattern)在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态
- 可以这样理解备忘录模式:现实生活中的备忘录是用来记录有些要去做的事情,或者是记录已经达成的共同意见,以防忘记了。而在软件层面,备忘录模式有这相同的含义,备忘录对象用来记录一个对象的某种状态,或者某些数据,当要做回退的时,可以从备忘录里获取到原来的对数据进行恢复操作
- 备忘录模式属于行为模式
备忘录模式的注意事项和细节
- 给用户提供了一种可恢复状态的机制,可以使用户比较方便的恢复到历史的某个状态
- 实现了信息的封装,使得用户不需要关心状态的保存细节
- 如果类的成员变量过多,势必会占用比较大的资源,而且一次保存都会消耗一定量的内存,这个需要注意
- 使用的场景:1.后悔药 2.游戏存档 3.Windows里的ctri + z 4.ie的后退 5.数据库的事务管理
- 为了节约内存,备忘录模式和原型模式可以配合使用
代码实现
使用备忘录模式实现游戏角色大战后恢复到大战前的状态
//游戏角色
public class GameRole {
private int vit; //攻击力
private int def; //防御力
//创建备忘录Memento,即根据游戏角色当前状态得到Memento
public Memento createMemento() {
return new Memento(vit, def);
}
public void recoverGameRoleFromMemento(Memento memento) {
this.vit = memento.getVit();
this.def = memento.getDef();
}
public void display() {
System.out.println("攻击力:" + vit + " 防御力:" + def);
}
public int getVit() {
return vit;
}
public void setVit(int vit) {
this.vit = vit;
}
public int getDef() {
return def;
}
public void setDef(int def) {
this.def = def;
}
}
//备忘录对象
public class Memento {
private int vit; //攻击力
private int def; //防御力
public Memento(int vit, int def) {
this.vit = vit;
this.def = def;
}
public int getVit() {
return vit;
}
public void setVit(int vit) {
this.vit = vit;
}
public int getDef() {
return def;
}
public void setDef(int def) {
this.def = def;
}
@Override
public String toString() {
return "Memento [vit=" + vit + ", def=" + def + "]";
}
}
//守护者对象,保存游戏角色的状态
public class Carktaker {
//保存多次状态
private List<Memento> list = new ArrayList<>();
//对多个游戏角色保存状态
// private Map<String, List<Memento>> map;
public void add(Memento memento) {
list.add(memento);
}
//获取到第index个备忘录对象
public Memento get(int index) {
return list.get(index);
}
}
//客户端
public class Client {
public static void main(String[] args) {
GameRole gameRole = new GameRole();
gameRole.setDef(100);
gameRole.setVit(100);
//大战前状态
System.out.println("大战前状态");
gameRole.display();
Carktaker carktaker = new Carktaker();
carktaker.add(gameRole.createMemento());
System.out.println("和boss大战后的状态");
//大战后属性降低
gameRole.setDef(80);
gameRole.setVit(80);
// carktaker.add(gameRole.createMemento());
gameRole.display();
System.out.println("恢复状态");
gameRole.recoverGameRoleFromMemento(carktaker.get(0));
gameRole.display();
}
}