备忘录模式Memento
场景:
-Word文档编辑时,电脑死机或者断电,再次打开时,word提醒恢复之前的文档
-文件的撤回
核心:
-就是保存某个对象内部状态的拷贝,这样以后就可以将该对象恢复到原先的状态
结构:
-源发器类Originator(需要备忘的对象,内部可以创建备忘录,用于记录当前时刻它的内部状态,并可使用备忘录回恢复内部状态)
-备忘录类Menmeto9(负责存储Originator对象的内部状态,并可防止Originator以外的其他对象访问备忘录)
-负责人类CareTaker(负责管理备忘录类)
备忘点较多时:
-将备忘录压栈:
public class CareTaker{
private Memento memento;
private Stack<Memento> stack=new Stack<>();
}
-将多个备忘录对象,序列化和持久化(存在硬盘上)
开发中的场景:
-棋类游戏中,悔棋
-撤销操作
-数据库软件中,事务管理中的回滚操作
-PS中的历史记录
/**
* 源发器类
* @author 小帆敲代码
*
*/
public class Emp {
private String ename;
private int age;
private double salary;
//构建备忘录对象
public Memento getMemento() {
return new Memento(this);
}
//进行数据恢复,恢复成指定备忘录对象的值
public void recovery(Memento m) {
this.setEname(m.getEname());
this.setAge(m.getAge());
this.setSalary(m.getSalary());
}
public Emp(String ename, int age, double salary) {
this.ename = ename;
this.age = age;
this.salary = salary;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
/**
* 备忘录
* @author 小帆敲代码
*
*/
public class Memento {
private String ename;
private int age;
private double salary;
public Memento(Emp e) {
this.ename = e.getEname();
this.age = e.getAge();
this.salary = e.getSalary();
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
* 负责人类
* 负责管理备忘录
* @author 小帆敲代码
*
*/
public class CareTaker {
private Memento mmt;
//private List<Memento> list=new ArrayList<>();
public CareTaker(Memento mmt) {
this.mmt = mmt;
}
}
return mmt;
}
this.mmt = mmt;
}
}
public static void main(String[] args) {
CareTaker ct= new CareTaker();
Emp e=new Emp("小张",18,10000);
System.out.println("第一次打印对象:"+e.getEname()+"---"+e.getAge()+"---"+e.getSalary());
//做备忘
ct.setMmt(e.getMemento());
e.setAge(30);
e.setEname("老张");
e.setSalary(10000000);
System.out.println("第二次打印对象:"+e.getEname()+"---"+e.getAge()+"---"+e.getSalary());
//恢复
e.recovery(ct.getMmt());
System.out.println("第三次打印对象:"+e.getEname()+"---"+e.getAge()+"---"+e.getSalary());
}
}
