备忘录模式是一种软件设计模式:在不破坏封闭的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。
以保存游戏进度为例,在游戏角色大战Boss前将该角色的状态存储,与Boss作战后角色的各项能力会下降,如果没有通关,则可利用备忘录进行恢复到战前状态。
游戏角色类:
package
com.zyh.designpattern.memento;
public
class
PlayRole {
private
int
vitality;
private
int
aggressivity;
private
int
defencivity;
public
PlayRole(
int
vitality,
int
aggressivity,
int
defencivity) {
super
();
this
.vitality = vitality;
this
.aggressivity = aggressivity;
this
.defencivity = defencivity;
}
public
PlayRole() {}
public
int
getVitality() {
return
vitality;
}
public
void
setVitality(
int
vitality) {
this
.vitality = vitality;
}
public
int
getAggressivity() {
return
aggressivity;
}
public
void
setAggressivity(
int
aggressivity) {
this
.aggressivity = aggressivity;
}
public
int
getDefencivity() {
return
defencivity;
}
public
void
setDefencivity(
int
defencivity) {
this
.defencivity = defencivity;
}
public
RoleMemento createMemento() {
RoleMemento memento =
new
RoleMemento();
memento.setAggressivity(aggressivity);
memento.setDefencivity(defencivity);
memento.setVitality(vitality);
return
memento;
}
public
void
setMemento(RoleMemento memento) {
this
.aggressivity = memento.getAggressivity();
this
.defencivity = memento.getDefencivity();
this
.vitality = memento.getVitality();
}
public
void
showState() {
System.out.println(
"攻击力:"
+
this
.aggressivity +
"|防御力:"
+
this
.defencivity
+
"|生命力:"
+
this
.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
|
package
com.zyh.designpattern.memento;
public
class
RoleMemento {
private
int
vitality;
private
int
aggressivity;
private
int
defencivity;
public
int
getVitality() {
return
vitality;
}
public
void
setVitality(
int
vitality) {
this
.vitality = vitality;
}
public
int
getAggressivity() {
return
aggressivity;
}
public
void
setAggressivity(
int
aggressivity) {
this
.aggressivity = aggressivity;
}
public
int
getDefencivity() {
return
defencivity;
}
public
void
setDefencivity(
int
defencivity) {
this
.defencivity = defencivity;
}
}
|
1
2
3
4
5
6
7
8
9
10
|
package
com.zyh.designpattern.memento;
public
class
Caretaker {
RoleMemento memento;
public
RoleMemento getMemento() {
return
memento;
}
public
void
setMemento(RoleMemento memento) {
this
.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
26
27
|
package
com.zyh.designpattern.memento;
public
class
Client {
public
static
void
main(String[] args) {
// 测试程序
// 新建角色
PlayRole role =
new
PlayRole(
100
,
100
,
100
);
// 新建管理者
Caretaker taker =
new
Caretaker();
// 角色初始状态
System.out.println(
"游戏刚开始,角色各属性:"
);
role.showState();
// 利用备忘录模式保存当前状态
System.out.println(
"\n【保存游戏状态!】\n"
);
taker.setMemento(role.createMemento());
role.setAggressivity(
20
);
role.setDefencivity(
30
);
role.setVitality(
0
);
// 大战过后,角色能力值下降
System.out.println(
"与Boss对战后,角色各项能力已大大下降:"
);
role.showState();
// 恢复保存的角色状态
role.setMemento(taker.getMemento());
System.out.println(
"\n【恢复保存的角色状态!】"
);
System.out.println(
"\n恢复后角色的当前状态:"
);
role.showState();
}
}
|