设计模式之备忘录模式

 代码实现

/**
 * 源发器类
 * @author bzhx
 * 2017年3月15日
 */
public class Emp {

    private String ename;
    private int age;
    private double salary;
    
    
    //备忘操作,并返回备忘录对象
    public EmpMemento memento(){
        return new EmpMemento(this);
    }
    
    //进行数据恢复,恢复成指定备忘录对象的值
    public void recovery(EmpMemento mmt){
        this.ename = mmt.getEname();
        this.age = mmt.getAge();
        this.salary  = mmt.getSalary();
    }
    
    public Emp(String ename, int age, double salary) {
        super();
        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 bzhx
 * 2017年3月15日
 */
public class EmpMemento {

    private String ename;
    private int age;
    private double salary;
    
    public EmpMemento(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 bzhx
 * 2017年3月15日
 */
public class CareTaker {

    private EmpMemento memento;
    
//    private List<EmpMemento> list = new ArrayList<EmpMemento>();

    public EmpMemento getMemento() {
        return memento;
    }

    public void setMemento(EmpMemento memento) {
        this.memento = memento;
    }
    
    
}
负责人类
public class Client {

    public static void main(String[] args) {
        CareTaker taker = new CareTaker();
        
        Emp emp = new Emp("高琪",18,900);
        System.out.println("第一次打印对象:" + emp.getEname() + "----" + emp.getAge()+"----"+emp.getSalary());
        
        taker.setMemento(emp.memento()); //备忘一次
        
        emp.setAge(38);
        emp.setEname("马奇");
        emp.setSalary(8888);
        System.out.println("第二次打印对象:" + emp.getEname() + "----" + emp.getAge()+"----"+emp.getSalary());
        
        emp.recovery(taker.getMemento()); //恢复到备忘录对象保存的状态
        System.out.println("第三次打印对象:" + emp.getEname() + "----" + emp.getAge()+"----"+emp.getSalary());
        
    } 
}
测试
第一次打印对象:高琪----18----900.0
第二次打印对象:马奇----38----8888.0
第三次打印对象:高琪----18----900.0
结果
原文地址:https://www.cnblogs.com/qingdaofu/p/7478250.html