📅  最后修改于: 2020-12-21 02:04:32             🧑  作者: Mango
记忆模式用于将对象的状态恢复到先前的状态。记忆模式属于行为模式类别。
记忆模式使用三个演员类。备忘录包含要恢复的对象的状态。发起者在Memento对象中创建并存储状态,看守对象负责从Memento恢复对象状态。我们创建了Memento , Originator和CareTaker类。
MementoPatternDemo,我们的演示课,将使用看守者和发起者对象,显示对象状态的恢复。
创建Memento类。
记忆库
public class Memento {
private String state;
public Memento(String state){
this.state = state;
}
public String getState(){
return state;
}
}
创建发起者类
Originator.java
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类
CareTaker.java
import java.util.ArrayList;
import java.util.List;
public class CareTaker {
private List mementoList = new ArrayList();
public void add(Memento state){
mementoList.add(state);
}
public Memento get(int index){
return mementoList.get(index);
}
}
使用CareTaker和Originator对象。
MementoPatternDemo.java
public class MementoPatternDemo {
public static void main(String[] args) {
Originator originator = new Originator();
CareTaker careTaker = new CareTaker();
originator.setState("State #1");
originator.setState("State #2");
careTaker.add(originator.saveStateToMemento());
originator.setState("State #3");
careTaker.add(originator.saveStateToMemento());
originator.setState("State #4");
System.out.println("Current State: " + originator.getState());
originator.getStateFromMemento(careTaker.get(0));
System.out.println("First saved State: " + originator.getState());
originator.getStateFromMemento(careTaker.get(1));
System.out.println("Second saved State: " + originator.getState());
}
}
验证输出。
Current State: State #4
First saved State: State #2
Second saved State: State #3