备忘录模式

类图

代码

Mementor

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
class Mementor{
private Integer hp;
private Integer mp;

public Mementor(Integer hp, Integer mp) {
this.hp = hp;
this.mp = mp;
}

public Integer getHp() {
return hp;
}

public void setHp(Integer hp) {
this.hp = hp;
}

public Integer getMp() {
return mp;
}

public void setMp(Integer mp) {
this.mp = mp;
}
}

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
36
37
38
39
40
41
42
class Role{
private Integer hp;
private Integer mp;

public Role(Integer hp, Integer mp) {
this.hp = hp;
this.mp = mp;
}

public Integer getHp() {
return hp;
}

public void setHp(Integer hp) {
this.hp = hp;
}

public Integer getMp() {
return mp;
}

public void setMp(Integer mp) {
this.mp = mp;
}

public void setMementor(Mementor mementor){
this.hp = mementor.getHp();
this.mp = mementor.getMp();
}

public Mementor createMementor(){
return new Mementor(this.hp, this.mp);
}

@Override
public String toString() {
return "Role{" +
"hp=" + hp +
", mp=" + mp +
'}';
}
}

Caretaker

1
2
3
4
5
6
7
8
9
10
11
12
class CareTaker{

private Mementor mementor;

public Mementor getMementor() {
return mementor;
}

public void saveMementor(Mementor mementor) {
this.mementor = mementor;
}
}

测试类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Main {
public static void main(String args[]){
Role role = new Role(100, 100);
System.out.println("大战BOSS前," + role);

CareTaker careTaker = new CareTaker();
careTaker.saveMementor(role.createMementor());

role.setHp(20);
role.setMp(20);

System.out.println("战斗后," + role);

role.setMementor(careTaker.getMementor());

System.out.println("读档后:" + role);

}
}

总结

概述

1.什么是备忘录模式

一个对象中一般都封装了很多属性,这些属性的值会随着程序的运行而变化。当我们需要保存某一时刻对象的某些值的时候,我们就再创建一个对象,将当前对象中的一些属性保存到新的对象中,当我们需要恢复的时候再从新的对象中取出属性值即可。这种想法就是备忘录模式

2.为什么需要caretaker类

为了不违背迪米特原则,只和朋友类交流,备份类不是朋友,系统需求只是在某个点创建备份

3.参考链接

https://www.cnblogs.com/chenssy/p/3341526.html

http://itfish.net/article/42940.html

http://blog.csdn.net/u010425776/article/details/48008713

优点

给用户提供了一种可以恢复状态的机制,方便的回到历史某个状态

实现了信息的封装,使得不用不需要关心状态保存的细节

缺点

当类的成员变量过多,会比较消耗资源

当类的成员变量发生变化,会违反开闭原则