设计模式-备忘录模式(Memento)

备忘录模式是行为模式之一,他的作用是备份对象内部信息,并在需要的时候恢复以前对象的信息。

 

角色和职责:

1.原生者(Originator)-Person:

  原对象

2.备忘录(Memento) -Memento:

 该对象由Originator创建,主要用来保存Originator的内部信息

3.管理者(CareTaker):

 负责在适当的时候,保存恢复Originator对象的信息

 

UML图:

具体源码:

/**
 * 原生类
 */
public class Person {
    private String name;//姓名
    private int age;//年龄

    public Person(String name,int age){
        this.name = name;
        this.age = age;
    }

    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 Memento createMemento(){
        return new Memento(name,age);
    }

    //回滚备份
    public void callback(Memento memento){
        this.name = memento.getName();
        this.age = memento.getAge();
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
/**
 * 备份类
 */
public class Memento {
    private String name;//姓名
    private int age;//年龄

    public Memento(String name,int age){
        this.name = name;
        this.age = age;
    }

    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 class CareTaker {
    private Memento memento;//备份对象
    public CareTaker(Memento memento){
        this.memento = memento;
    }

    public Memento getMemento() {
        return memento;
    }

    public void setMemento(Memento memento) {
        this.memento = memento;
    }
}
public class Main {
    public static void main(String[] args) {
        Person person = new Person("张三",15);
        System.out.println(person.toString());
        CareTaker careTaker = new CareTaker(person.createMemento());//person创建一个备份,交给careTaker来管理

        person.setAge(16);//修改age
        System.out.println(person.toString());
        //回滚
        person.callback(careTaker.getMemento());
        System.out.println(person.toString());
    }
}

结果:

Person{name='张三', age=15}
Person{name='张三', age=16}
Person{name='张三', age=15}

 

应用场景:

一个类需要做备份时,做回滚时。

 

源码地址:https://github.com/qjm201000/design_pattern_memento.git

 

posted @ 2018-12-12 16:25  qjm201000  阅读(194)  评论(0编辑  收藏  举报