作用
- 在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。
何时使用
- 很多时候我们总是需要记录一个对象的内部状态,这样做的目的就是为了允许用户取消不确定或者错误的操作,能够恢复到他原先的状态,使得他有"后悔药"可吃。
优点
- 给用户提供了一种可以恢复状态的机制,可以使用户能够比较方便地回到某个历史的状态
- 实现了信息的封装,使得用户不需要关心状态的保存细节。
实例
/**
* @Author: create_By: chenxin
* @Data:Created in 2018/9/26 13:28
* @Version:
* @Acton: 备忘录类
*/
public class EmpMemento {
private String ename;
private int age;
private double 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;
}
public EmpMemento(Emp e) {
this.age = e.getAge();
this.ename = e.getEname();
this.salary = e.getSalary();
}
}
/**
* @Author: create_By: chenxin
* @Data:Created in 2018/9/26 13:26
* @Version:
* @Acton: 源发器类
*/
public class Emp {
private String ename;
private int age;
private double salary;
//进行备忘录操作,并返回备忘录对象
public EmpMemento empMemento(){
return new EmpMemento(this);
}
//进行数据恢复,恢复成指定备忘录对象的值
public void recovery(EmpMemento empMemento){
this.age = empMemento.getAge();
this.ename = empMemento.getEname();
this.salary = empMemento.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;
}
public Emp(String ename, int age, double salary) {
this.ename = ename;
this.age = age;
this.salary = salary;
}
}
/**
* @Author: create_By: chenxin
* @Data:Created in 2018/9/26 13:33
* @Version:
* @Acton: 负责人类,管理备忘录对象
*/
public class CareTaker {
private EmpMemento empMemento;
public EmpMemento getEmpMemento() {
return empMemento;
}
public void setEmpMemento(EmpMemento empMemento) {
this.empMemento = empMemento;
}
}
/**
* @Author: create_By: chenxin
* @Data:Created in 2018/9/26 13:34
* @Version:
* @Acton:
*/
public class TestMementoDemo {
public static void main(String[] args){
test1();
}
public static void test1(){
CareTaker taker = new CareTaker();
Emp emp = new Emp("陈新", 22, 10.5);
System.out.println("第一次创建对象:"+ emp.getEname()+"___"+ emp.getAge()+"___"+ emp.getSalary()+"___");
taker.setEmpMemento(emp.empMemento()); //备份
emp.setEname("cx");
emp.setAge(18);
emp.setSalary(100);
System.out.println("修改后的对象:"+ emp.getEname()+"___"+ emp.getAge()+"___"+ emp.getSalary()+"___");
emp.recovery(taker.getEmpMemento());
System.out.println("恢复备忘录的对象:"+ emp.getEname()+"___"+ emp.getAge()+"___"+ emp.getSalary()+"___");
}
}
关系结构图