Design Patterns - Memento

design-patterns

Design Patterns - Behavioral - Memento:

Memento pattern is used to restore state of an object to a previous state. 
Memento pattern falls under behavioral pattern category.

Memento pattern uses three actor classes. Memento contains state of an object 
to be restored. Originator creates and stores states in Memento objects and 
Caretaker object is responsible to restore object state from Memento. We have 
created classes Memento, Originator and CareTaker. 

// Step 1: Create Memento class.
public class Memento {
   private String state;

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

   public String getState(){
      return state;
   }    
}

// Step 2: Create Originator class
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: Create CareTaker class
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: Use CareTaker and Originator objects.
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());
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License