- 备忘录角色
public class Memento {
private String state;
public Memento(String state) {
this.state = state;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
- 管理者角色
public class Caretaker {
private Memento memento;
public Memento getMemento() {
return memento;
}
public void setMemento(Memento memento) {
this.memento = memento;
}
}
- 发起人角色
public class Originator {
//备份数据
private String state;
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
//创建备份数据
public Memento createMemento() {
return new Memento(this.getState());
}
//恢复备份数据
public void restoreMemento(Memento memento) {
this.setState(memento.getState());
}
}
- 场景使用
//定义发起人角色
Originator originator =new Originator();
//创建备份管理者角色
Caretaker caretaker =new Caretaker();
//创建备份状态
caretaker.setMemento(originator.createMemento());
//恢复备份状态
originator.restoreMemento(caretaker.getMemento());
网友评论