一、简介
1.1 模式定义
在不破坏封装的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样可以在以后将对象恢复到原先保存的状态。它是一中对象行为模式,其别名为Token。
1.2 适用场景
1)保存一个对象在某一个时刻的状态或部分状态,这样以后需要时它能够恢复到先前的状态。
2)如果用一个接口来让其他对象得到这些状态,将会暴露对象额实现细节并破坏对象的封装性,一个对象不希望外界直接访问其内部状态,通过负责人可以间接访问其内部状态。
1.3 优点
1)提供了一种状态恢复的实现机制,使得用户可以方便地回到一个特定的历史步骤,当新的状态无效或者存在问题时,可以使用先前存储起来的备忘录将状态恢复。
2)实现了信息的封装,一个备忘录对象时一种源发器对象的表示,不会被其他代码改动,这种模式简化了原发器对象,备忘录只保存原发器的状态,采用堆栈来存储备忘录对象可以实现多次撤销操作,可以通过在负责人中定义集合对象来存储对个备忘录。
1.4 缺点
资源消耗过大,如果类的成员变量太多美酒不可避免占用大量内存,而且每保存一次对象的状态都需要消耗内存资源,如果知道这一点大家就容易理解为什么一些提供了撤销功能的软件在运行时所需的内存和硬盘空间比较大了。
二、示例
2.1 结构图
2.2 原发器UserInfoDTO(用户信息类)
public class UserInfoDTO {
private String account;
private String password;
private String telNo;
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getTelNo() {
return telNo;
}
public void setTelNo(String telNo) {
this.telNo = telNo;
}
public Memento saveMemento() {
return new Memento(account, password, telNo);
}
public void restorMemento(Memento memento) {
this.account = memento.getAccount();
this.password = memento.getPassword();
this.telNo = memento.getTelNo();
}
public void show() {
System.out.println("Accont: " + account);
System.out.println("Password: " + password);
System.out.println("TelNo: " + telNo);
}
}
2.3 备忘录Memento
public class Memento {
private String account;
private String password;
private String telNo;
public Memento(String account, String password, String telNo) {
this.account = account;
this.password = password;
this.telNo = telNo;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getTelNo() {
return telNo;
}
public void setTelNo(String telNo) {
this.telNo = telNo;
}
}
2.4 负责人Caretaker
public class Caretaker {
private Memento memento;
public Memento getMemento() {
return memento;
}
public void setMemento(Memento memento) {
this.memento = memento;
}
}

193






