设计模式系列:备忘录模式

概念

备忘录保存的是类内部状态。在适当的时候可以用来恢复当时的类状态。还原现场。

实现

类图

图片

代码

  • Originator
    执行者,封装备忘录具体属性信息。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    package com.littlehui.design.memoto;

    /**
    * @Description TODO
    * @ClassName Originator
    * @Author littlehui
    * @Date 2020/4/7 14:45
    * @Version 1.0
    **/
    public class Originator {

    private String state;

    /**
    * 创建一个新的备忘录对象
    */
    public Memento createMemento(){
    return new Memento(state);
    }

    /**
    * 将发起者的状态恢复到备忘录的状态
    */
    public void restore(Memento memento){
    this.state = memento.getState();
    }

    public String getState() {
    return state;
    }

    public void setState(String state) {
    this.state = state;
    }
    }
  • Caretaker
    备忘录管理者。包含一个备忘录具体对象,可以是list。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.littlehui.design.memoto;

/**
* @Description TODO
* @ClassName Caretaker
* @Author littlehui
* @Date 2020/4/7 14:46
* @Version 1.0
**/
public class Caretaker {

private Memento mMemento;

public Memento restoreMemento(){
return mMemento;
}

public void storeMemengto(Memento memento){
this.mMemento = memento;
}
}
  • Memento
    备忘录的具体类。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.littlehui.design.memoto;

/**
* @Description TODO
* @ClassName Memento
* @Author littlehui
* @Date 2020/4/7 14:45
* @Version 1.0
**/
public class Memento {

private String state;

public Memento(String state){
this.state = state;
}

public String getState() {
return state;
}

public void setState(String state) {
this.state = state;
}
}
  • Client
    执行流程
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.littlehui.design.memoto;

/**
* @Description TODO
* @ClassName Client
* @Author littlehui
* @Date 2020/4/7 14:45
* @Version 1.0
**/
public class Client {

public static void main(String[] args) {

//发起 并初始化
Originator originator = new Originator();
originator.setState("state1");

//备忘录管理
Caretaker caretaker = new Caretaker();
caretaker.storeMemengto(originator.createMemento());
originator.setState("state2");
System.out.println(originator);

//备忘录 恢复
originator.restore(caretaker.restoreMemento());
System.out.println(originator);
}
}

场景

比如在玩游戏保存游戏进度的时候可以用来实现回退功能。回退到上一个保存点。等等

总结

  • 优点
    备忘录模式存在的意义也是在于他的回复机制。并且其特点是在用户不必关心类的内部细节情况下完成了。
    实现了信息封装。

  • 缺点
    由于备忘录的保存需要额外的存储空间,所以在类属性多的情况下,多次的备忘录操作比较消耗资源。