备忘录模式(Memento Pattern)
半塘 2024/4/1 Java进阶
在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。本质就是备份一下对象,并提供重置方式。
# 1、备忘录模式案例
public interface Memento {
// 加总
int sum();
// 备份
Memento backup();
// 重置
void reset(Memento memento);
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
@Data
public class NumberMemento implements Memento{
private int num1;
private int num2;
public NumberMemento(int num1, int num2) {
this.num1 = num1;
this.num2 = num2;
}
@Override
public int sum() {
return num1+num2;
}
@Override
public Memento backup() {
return new NumberMemento(num1,num2);
}
@Override
public void reset(Memento memento) {
this.num1 = ((NumberMemento) memento).getNum1();
this.num2 = ((NumberMemento) memento).getNum2();
}
}
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
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
public class ClientTest {
public static void main(String[] args) {
NumberMemento n1 = new NumberMemento(3,5);
System.out.println(n1.sum());
// 备份
Memento backup = n1.backup();
n1.setNum1(6);
n1.setNum2(10);
System.out.println(n1.sum());
// 撤回到备份状态
n1.reset(backup);
System.out.println(n1.sum());
}
}
/**
* 输出结果:
* 8
* 16
* 8
* /
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23