Design Pattern 简明教程

Design Patterns - Memento Pattern

备忘录模式用于将对象的某一状态还原到以前的某个状态。备忘录模式归属于行为模式类别。

Implementation

备忘录模式使用三个参与者类。备忘录包含要还原的对象的状态。发起者创建和存储状态在备忘录对象中,看护者对象负责从备忘录还原对象的状态。我们创建了 Memento、Originator 和 CareTaker 类。

MementoPatternDemo,我们的演示类,将使用 CareTaker 和 Originator 对象来展示对象状态的还原。

memento pattern uml diagram

Step 1

创建 Memento 类。

Memento.java

public class Memento {
   private String state;

   public Memento(String state){
      this.state = state;
   }

   public String getState(){
      return state;
   }
}

Step 2

创建 Originator 类

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();
   }
}

Step 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);
   }
}

Step 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());
   }
}

Step 5

验证输出。

Current State: State #4
First saved State: State #2
Second saved State: State #3