设计模式 备忘录模式

  • 设计模式 - 备忘录模式

    备忘录模式用于将对象的状态恢复到先前的状态。备忘录模式属于行为模式类别。
  • 实例

    备忘录模式使用三个类。Memento 包含要恢复的对象的状态。发起者在Memento对象中创建并存储状态,Originator对象负责从Memento恢复对象状态。我们创建了Memento,Originator和CareTaker类。,我们的演示类MementoPatternDemo,将使用Originator和CareTaker对象,显示对象状态的恢复。
    dp
    第1步 - 创建Memento类。Memento.java
    
    public class Memento {
       private String state;
    
       public Memento(String state){
          this.state = state;
       }
    
       public String getState(){
          return state;
       }    
    }
    
    第2步 - 创建发起者类。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();
       }
    }
    
    第3步 - 创建CareTaker类。CareTaker.java
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class CareTaker {
       private List<Memento> mementoList = new ArrayList<Memento>();
    
       public void add(Memento state){
          mementoList.add(state);
       }
    
       public Memento get(int index){
          return mementoList.get(index);
       }
    }
    
    步骤4 - 使用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());
       }
    }
    
    第5步 - 验证输出。
    
    Current State: State #4
    First saved State: State #2
    Second saved State: State #3