备忘录模式
GuoJun 2022-05-24 设计模式
# 简介
备忘录模式(Memento Pattern)保存一个对象的某个状态,以便在适当的时候恢复对象。备忘录模式属于行为型模式。
# 实现
- 创建Memento类
public class Memento {
private String state;
public Memento(String state){
this.state = state;
}
public String getState(){
return state;
}
}
- 创建Originator类
public class Originator {
private String state;
public void setState(String state){
this.state = state;
}
public String getState(){
return state;
}
public Memento saveStateToMemento(){
return new Memento(state);
}
public void getStateFromMemento(Memento memento){
state = memento.getState();
}
}
- 创建CareTaker类
public class CareTaker {
private List<Memento> mementoList = new ArrayList<>();
public void add(Memento state){
mementoList.add(state);
}
public Memento get(int index){
return mementoList.get(index);
}
}
- 使用CareTaker和Originator对象
public class MementoPatternDemo {
public static void main(String[] args) {
Originator originator = new Originator();
CareTaker careTaker = new CareTaker();
originator.setState("状态1");
originator.setState("状态2");
careTaker.add(originator.saveStateToMemento());
originator.setState("状态3");
careTaker.add(originator.saveStateToMemento());
originator.setState("状态4");
System.out.println("当前状态: "+originator.getState());
originator.getStateFromMemento(careTaker.get(0));
System.out.println("第一个状态: " + originator.getState());
originator.getStateFromMemento(careTaker.get(1));
System.out.println("第二个状态: " + originator.getState());
}
}