携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第10天,点击查看活动详情
1.意图:
在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态
2.适用性:
必须保存一个对象在某一个时刻的(部分)状态,这样以后需要时它才能恢复到先前的状态。
3.备忘录(Memento)模式构成:
- 备忘录(Memento)角色:保持原发器(Originator)的内部状态,根据原发器来决定保存哪些内部的状态。 备忘录可以有效地利用两个接口。看管者只能调用狭窄(功能有限)的接口——它只能传递备忘录给其他对象。而原发器可以调用一饿宽阔(功能强大)的接口,通过这个接口可以访问所有需要的数据,使原发器可以返回先前的状态。
- 原发器(Originator)角色:创建一个备忘录,记录它当前内部状态。可以利用一个备忘录来恢复它的内部状态。
- 看管者(Caretaker)角色:只负责看管备忘录。不可以对备忘录的内容操作或者检查。
4.备忘录模式UML类图:
5.备忘录模式UML序列图:
6.代码示例:
备忘录角色:
public class Memento {
public String name;
public String phone;
public double budget;
public Memento(String name, String phone, double budget) {
this.name = name;
this.phone = phone;
this.budget = budget;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public double getBudget() {
return budget;
}
public void setBudget(double budget) {
this.budget = budget;
}
}
看管者角色:
public class Caretaker {
public Memento memento;
public Memento getMemento() {
return memento;
}
public void setMemento(Memento memento) {
this.memento = memento;
}
}
原发器角色:
public class Originator {
public String name;
public String phone;
public double budget;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public double getBudget() {
return budget;
}
public void setBudget(double budget) {
this.budget = budget;
}
// 保存备忘录
public Memento saveMemento() {
return new Memento(name, phone, budget);
}
// 恢复备忘录
public void restoreMemento(Memento memento) {
name = memento.name;
phone = memento.phone;
budget = memento.budget;
}
// 显示信息
public void show() {
System.out.println("销售期望:");
System.out.println("名字:" + name);
System.out.println("电话:" + phone);
System.out.println("预算:" + budget);
}
}
客户端:
public class Client {
public static void main(String[] args) {
Originator originator = new Originator();
originator.name = "张三";
originator.phone = "123456";
originator.budget = 1000;
originator.show();
Caretaker caretaker = new Caretaker();
caretaker.memento = originator.saveMemento();
originator.name = "李四";
originator.phone = "987654";
originator.budget = 2000;
originator.show();
originator.restoreMemento(caretaker.getMemento());
originator.show();
}
}