GOF23设计模式(十五)

GOF设计模式之备忘录模式(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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
* 源发器类
*
*/
public class Emp {
private String name;
private int age;
private double salary;


//备忘录操作
public EmpMemento memento() {
return new EmpMemento(this);
}

//进行数据恢复,恢复成指定备忘录对象的值
public void recovery(EmpMemento mmt) {
this.name=mmt.getName();
this.age=mmt.getAge();
this.salary=mmt.getSalary();
}

public Emp(String name, int age, double salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}

备忘录

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
/**
* 备忘录类
*
*/
public class EmpMemento {
private String name;
private int age;
private double salary;
public EmpMemento(Emp e) {
this.name=e.getName();
this.age=e.getAge();
this.salary=e.getSalary();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}

负责人

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* 负责人类
* 管理备忘录对象
*
*/
public class CareTaker {
private EmpMemento memento;

public EmpMemento getMemento() {
return memento;
}

public void setMemento(EmpMemento memento) {
this.memento = memento;
}
}

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Client {

public static void main(String[] args) {
CareTaker taker = new CareTaker();
Emp emp = new Emp("小四",19,1000);
System.out.println("Once"+"年龄:"+emp.getAge()+",姓名:"+emp.getName()
+",工资:"+emp.getSalary());
taker.setMemento(emp.memento());//记录一次
emp.setAge(20);emp.setName("大四");emp.setSalary(1200);
System.out.println("Twice"+"年龄:"+emp.getAge()+",姓名:"+emp.getName()
+",工资:"+emp.getSalary());
emp.recovery(taker.getMemento());//恢复
System.out.println("-----"+"年龄:"+emp.getAge()+",姓名:"+emp.getName()
+",工资:"+emp.getSalary());
}
}

结果

Once年龄:19,姓名:小四,工资:1000.0
Twice年龄:20,姓名:大四,工资:1200.0
—–年龄:19,姓名:小四,工资:1000.0

原创技术分享,您的支持将鼓励我继续创作
0%