设计模式学习(二十):备忘录模式

备忘录模式

备忘录模式是一种行为型模式。

用于记录对象的某个瞬间,类似快照的功能,

应用实例:

  • 游戏中的「后悔药」;
  • 打游戏时的存档;
  • Windows 操作系统里的撤销操作( ctr + z );
  • 浏览器的后退功能。

一个简单的示例

通过序列化的方式将数据存盘,然后从盘中提取并反序列化数据。

public class Main {
    public static void main(String[] args) {
        Person person = new Person();
        person.name = "zhangsan";
        person.age = 12;
        new Main().save(person);
        new Main().load();
    }

    public void save(Person person) {
        File c = new File("/tank.data");
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(c));) {
            oos.writeObject(person);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void load() {
        File c = new File("/tank.data");
        try (ObjectInputStream oos = new ObjectInputStream(new FileInputStream(c));) {
            Person myTank = (Person) oos.readObject();
            System.out.println(myTank);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

注:其中的 Person 类需要实现序列化接口(即:实现 Serializable 接口)

public class Person implements Serializable {
    
 private static final long serialVersionUID = 8694061726340087034L;
 public String name;
    public int age;

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

上述示例的 UML 图如下

设计模式学习(二十):备忘录模式-小白菜博客

备忘录模式应用

  • Spring 中 StateManageableMessageContext.createMessagesMemento() 方法

UML 和 代码

UML 图

代码

更多

设计模式学习专栏

参考资料