Java Design Patterns Memento Patterns

Introduction

Memento Patterns capture and externalize an object's internal state without violating encapsulation.

Use case

  • In notepad we use undo by pressing ctrl+Z.

Example

class State {
   private String state;

   public State(String state) {
      this.state = state;
   }//from  w  w w . j av  a  2 s .  c  o  m

   public String getState() {
      return state;
   }
}

class Originator {
   private String state;
   private State m;

   public void setState(String state) {
      this.state = state;
      System.out.println("State at present : " + state);
   }
   public State OriginatorMemento() {
      m = new State(state);
      return m;
   }
   public void Revert(State memento) {
      System.out.println("Restoring to previous state...");
      state = memento.getState();
      System.out.println("State at present :" + state);
   }
}

class StateKeeper {
   private State _memento;

   public void SaveMemento(State m) {
      _memento = m;
   }

   public State RetrieveMemento() {
      return _memento;
   }
}

public class Main {
   public static void main(String[] args) {
      Originator o = new Originator();
      o.setState("First state");

      StateKeeper c = new StateKeeper();
      c.SaveMemento(o.OriginatorMemento());

      o.setState("Second state");

      o.Revert(c.RetrieveMemento());
   }
}



PreviousNext

Related