0%

备忘录模式

备忘录模式

在不破坏封装性的前提下,捕捉一个对象的内部状态,并在该对象之外保存这个状态,这样以后就可以将该对象恢复为原先保存的状态,用于保存和恢复内部状态

核心概念

  • Memento 备忘录,用于存储原发器对象的内部状态
  • Originator 原发器,使用备忘录来保存某个时刻原发器自身的状态,也可以使用备忘录来恢复内部状态
  • Caretaker 备忘录管理者,负责保存备忘录对象,但是不能对备忘录对象的内容进行操作或检查,并不一定要抽象出一个管理者来,备忘录放在哪里,哪里就是管理者
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/**
* 备忘录接口
* @author zh
* @date 2022/10/18 11:50
*/
public interface Memento {
}

/**
* 原发器
* @author zh
* @date 2022/10/18 11:51
*/
public class Origintor {
private String state;

public String getState() {
return state;
}

public void setState(String state) {
this.state = state;
}

public Memento createMemento(){
return new MementoImpl(state);
}

// 重置原发器状态,回到备忘录中的状态
public void setMemento(Memento memento){
MementoImpl memento1 = (MementoImpl) memento;
this.state = memento1.getState();
}

// 备忘录实现,私有内部类,不能被外部访问
private static class MementoImpl implements Memento{

private String state;

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

public String getState() {
return state;
}
}
}

/**
* 备忘录管理对象
* @author zh
* @date 2022/10/18 11:56
*/
public class Caretaker {
private Memento memento;

public Memento retriveMemento() {
return memento;
}

public void saveMemento(Memento memento) {
this.memento = memento;
}
}

public class Main {
public static void main(String[] args) {
Origintor origintor = new Origintor();
origintor.setState("init");
System.out.println("初始"+origintor.getState());

Memento memento = origintor.createMemento();
Caretaker caretaker = new Caretaker();
caretaker.saveMemento(memento);

origintor.setState("running");
System.out.println("运行"+origintor.getState());
origintor.setMemento(caretaker.retriveMemento());

System.out.println("回滚"+origintor.getState());


}
}

优缺点

优点

  • 更好的封装性

缺点

使用场景

  • 数据库连接的事务管理器
  • 提供一个可回滚的操作
  • 如果必须保存一个对象在某一时刻的全部或部分状态,方便以后需要的时候使用,可以把对象恢复到先前的状态,可以使用备忘录模式

欢迎关注我的其它发布渠道