备忘录模式

1.使用场景:

一系列的操作之后恢复原来的状态。实际的使用场景有事务的回滚操作等。

2.UML表示

在备忘录模式中有以下的几种对象:
2.1源发器:Originator
2.2备忘录类:Memento
2.3负责人CareTake
具体的UML示意图如下:

 

3.代码实现

 

首先定义Emp类:

public class Emp {
    private String name;
    private int age;
    private double salary;

    public Emp(String name, int age, double salary) {
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    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 memento(){
        return new EmpMemento(this);
    }
    //进行数据恢复,恢复成备忘录对象的值
    public void recovery(EmpMemento emto){
        this.name=emto.getName();
        this.age=emto.getAge();
        this.salary=emto.getSalary();
    }
}

定义EmpMemento类:

 

public class EmpMemento {
    private String name;
    private int age;
    private double salary;

    public EmpMemento(Emp e) {//这是关键
        this.name=e.getName();
        this.age=e.getAge();
        this.salary=e.getSalary();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    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;
    }

}

编写CareTaker类:

 

 

public class CareTaker {
    private EmpMemento memento;
    public EmpMemento getMemento() {
        return memento;
    }

    public void setMemento(EmpMemento memento) {
        this.memento = memento;
    }

}

最后给出测试类:

 

 

public class Client {
    public static void main(String[] args) {
        CareTaker careTaker=new CareTaker();
        Emp emp=new Emp("小强",90,900);
        System.out.println(emp.getName()+" "+emp.getAge()+" "+emp.getSalary());
        careTaker.setMemento(emp.memento());
        emp.setAge(9);
        System.out.println(emp.getName()+" "+emp.getAge()+" "+emp.getSalary());
        emp.recovery(careTaker.getMemento());
        System.out.println(emp.getName()+" "+emp.getAge()+" "+emp.getSalary());
    }
}

 

 

 

4.总结

 

备忘录模式保存了内部状态的拷贝,以后直接恢复即可。
代码地址:
https://github.com/memoryexplosion/design_pattern_review/tree/master/src/java/memeto

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值