How to Use Memento Design Pattern in Java


In following example, let’s us see how to implement Memento Pattern in Java.

Source Code

1)

package com.beginner.examples;

public class Memento1 {
	   private String state;
	 
	   public Memento1(String state){
	      this.state = state;
	   }
	   // get state
	   public String getState(){
	      return state;
	   }  
	}

2)

package com.beginner.examples;

public class Memento2 {
	   private String state;
	 
	   public void setState(String state){
	      this.state = state;
	   }
	 
	   public String getState(){
	      return state;
	   }
	   // save state
	   public Memento1 saveStateToMemento(){
	      return new Memento1(state);
	   }
	 
	   public void getStateFromMemento(Memento1 Memento){
	      state = Memento.getState();
	   }
	}

3)

package com.beginner.examples;

import java.util.ArrayList;
import java.util.List;
 
public class Memento3 {
   private List m = new ArrayList();
 
   public void add(Memento1 state){
      m.add(state);
   }
 
   public Memento1 get(int index){
      return m.get(index);
   }
}

4)

package com.beginner.examples;

public class MementoExample {
	   public static void main(String[] args) {
		  Memento2 o = new Memento2();
		  Memento3 c = new Memento3();
		  // set state
	      o.setState("#00");
	      // save state
	      c.add(o.saveStateToMemento());
	      // reset state
	      o.setState("#01");	 
	      System.out.println("Current State: " + o.getState());
	      // get first state
	      o.getStateFromMemento(c.get(0));
	      System.out.println("First saved State: " + o.getState());
	   }
	}

Output:

Current State: #01
First saved State: #00

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments