备忘录模式

在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态.这样以后就可以将该对象恢复到原先保存的状态.
快照模式和clone方式的区别在于此模式可以有选择性的保存.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package memento;

/**
* Created by hero on 17-2-19.
*/
public class RoleStateMemento {
private int vitality;

public RoleStateMemento(int vitality) {
this.vitality = vitality;
}

public int getVitality() {
return vitality;
}
}

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
package memento;

/**
* Created by hero on 17-2-19.
*/
public class GameRole {
private int vitality;
private int attack;

/**
* 创建备忘录
*/
public RoleStateMemento saveState() {
return new RoleStateMemento(vitality);
}

public void recoveryState(RoleStateMemento memento) {
//恢复时应注意是否为null
if (memento == null) return;
vitality = memento.getVitality();
}

public int getVitality() {
return vitality;
}

public void setVitality(int vitality) {
this.vitality = vitality;
}

public int getAttack() {
return attack;
}

public void setAttack(int attack) {
this.attack = attack;
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package memento;

import java.util.Stack;

/**
* 备忘录管理者
*/
public class Caretaker {
private Stack<RoleStateMemento> mementos;

public Caretaker() {
mementos = new Stack<RoleStateMemento>();
}

public void push(RoleStateMemento memento) {
mementos.push(memento);
}

public RoleStateMemento get() {
return mementos.pop();
}
}

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
package memento;

/**
* Created by hero on 17-2-19.
*/
public class Main {
public static void main(String[] args) {
Caretaker caretaker = new Caretaker();
GameRole role = new GameRole();
role.setVitality(10);
//备份
RoleStateMemento memento = role.saveState();
caretaker.push(memento);

role.setVitality(5);
memento = role.saveState();
caretaker.push(memento);
//恢复
role.recoveryState(caretaker.get());
System.out.println(role.getVitality());

role.recoveryState(caretaker.get());
System.out.println(role.getVitality());
}
}