【注意】最后更新于 January 25, 2018,文中内容可能已过时,请谨慎使用。
本文我们来讨论下java设计模式之备忘录模式。
备忘录模式,就是有点像备份了,记录下一个程序当前的状态,有人维护着,需要的时候就再恢复回来。
这个不就很像我们小时候玩游戏做的备份吗?或者更直接点说,就是我在这边刷好金币,备份下,发给你,全部都有这么多了。玩游戏很爽。
比如最近很火的旅行青蛙吧。我们得收集三叶草,给他买东西,等他回来,可是要一点一点攒好麻烦。如果有人刷好了发给我就好了。
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
|
package top.txiner.memento;
/**
* @author : hundred
* time: 18-1-25
* website : http://txiner.top
* 懵懂的小白
*/
public class Frog {
private int leaves;
public int getLeaves() {
return leaves;
}
public void setLeaves(int leaves) {
this.leaves = leaves;
}
public Memento saveState(){
return new Memento(this.leaves);
}
public void recoveryState(Memento m){
this.leaves=m.getAmount();
}
public void buy(){
this.leaves=0;
System.out.print("I buy a ham;");
System.out.println(this);
}
@Override
public String toString() {
return "I have " + this.leaves + " leaves";
}
}
|
我这个青蛙类,就是作为一个备忘的发起人,能够记录自己的状态,并且根据需要恢复回来。
我得创建备忘录了,能够存储下这些内容。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
public class Memento {
private int amount;
public Memento(int amount) {
this.amount = amount;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
}
|
突然,我想保存两个备份,一个是三叶草多的,一个是风景多的,那可该怎么办呢?来一个管理类嘛!
1
2
3
4
5
6
7
8
9
10
11
|
public class Manage {
private Memento memento;
public Memento getMemento() {
return memento;
}
public void setMemento(Memento memento) {
this.memento = memento;
}
}
|
好了,我们来玩下
1
2
3
4
5
6
7
8
9
10
11
12
|
public class Player {
public static void main(String[] args) {
Frog frog=new Frog();
frog.setLeaves(100);
System.out.println(frog);
Manage manage=new Manage();
manage.setMemento(frog.saveState());
frog.buy();
frog.recoveryState(manage.getMemento());
System.out.println(frog);
}
}
|
.................分割线....................
可以看到,这个模式用来恢复程序的一些运行状态挺好的,如果做了序列化存储的话,应该应用型更强。
ps,旅行青蛙不能备份!仅仅是个例子。