Memento Design Pattern Tutorial

Memento Design Pattern TutorialWelcome to my Memento Design Pattern Tutorial! The Memento design pattern provides a way to store previous states of an Object easily.

It has 3 main classes. Memento: The basic object that is stored in different states. Originator: Sets and Gets values from the currently targeted Memento. Creates new Mementos and assigns current values to them. Caretaker: Holds an ArrayList that contains all previous versions of the Memento. It can store and retrieve stored Mementos. All of the code is down below to help you learn.

If you think videos like this, it helps to tell Google

Share if you think a friend may like this

Code from the Memento Design Pattern Tutorial Video

MEMENTO.JAVA

// Memento Design Pattern
// Used stores an objects state at a point in time
// so it can be returned to that state later. It
// simply allows you to undo/redo changes on an Object

public class Memento {
	
	// The article stored in memento Object
	
	private String article;

	// Save a new article String to the memento Object
	
	public Memento(String articleSave) { article = articleSave; }
	
	// Return the value stored in article 
	
	public String getSavedArticle() { return article; }
	
}

ORIGINATOR.JAVA

// Memento Design Pattern

public class Originator{
	
	private String article;

	// Sets the value for the article
	
	public void set(String newArticle) { 
		System.out.println("From Originator: Current Version of Article\n"+newArticle+ "\n");
	    this.article = newArticle; 
	}

	// Creates a new Memento with a new article
	
	public Memento storeInMemento() { 
	    System.out.println("From Originator: Saving to Memento");
	    return new Memento(article); 
	}
	   
	// Gets the article currently stored in memento
	
	public String restoreFromMemento(Memento memento) {
		   
		article = memento.getSavedArticle(); 
	       
		System.out.println("From Originator: Previous Article Saved in Memento\n"+article + "\n");
		
		return article;
	   
	}
	
}

CARETAKER.JAVA

// Memento Design Pattern Tutorial

import java.util.ArrayList;

class Caretaker {
   
	// Where all mementos are saved
	
	ArrayList<Memento> savedArticles = new ArrayList<Memento>();

	// Adds memento to the ArrayList
	
	public void addMemento(Memento m) { savedArticles.add(m); }
   
	// Gets the memento requested from the ArrayList
	
	public Memento getMemento(int index) { return savedArticles.get(index); }
} 

TESTMEMENTO.JAVA

// Memento Design Pattern Tutorial

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class TestMemento extends JFrame{
   public static void main(String[] args) {
       
	   new TestMemento();
       
   }
   
   private JButton saveBut, undoBut, redoBut;
   
   // JTextArea(rows, columns)
   
   private JTextArea theArticle = new JTextArea(40,60);
   
   // ---------------------------------------------
   
   // Create a caretaker that contains the ArrayList 
   // with all the articles in it. It can add and
   // retrieve articles from the ArrayList
   
   Caretaker caretaker = new Caretaker();

   // The originator sets the value for the article,
   // creates a new memento with a new article, and 
   // gets the article stored in the current memento
   
   Originator originator = new Originator();
   
   int saveFiles = 0, currentArticle = 0;
   
   // ---------------------------------------------
   
   public TestMemento(){
	   
	   // Set basic information for the panel that will
	   // hold all the GUI elements
	   
	   this.setSize(750,780);
	   this.setTitle("Memento Design Pattern");
	   this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	   
	   JPanel panel1 = new JPanel();
	   
	   // Add label to the panel
	   
	   panel1.add(new JLabel("Article"));
	   
	   // Add JTextArea to the panel
	   
	   panel1.add(theArticle);
	   
	   // Add the buttons & ButtonListeners to the panel
	   
	   ButtonListener saveListener = new ButtonListener();
	   ButtonListener undoListener = new ButtonListener();
	   ButtonListener redoListener = new ButtonListener();
	   
	   saveBut = new JButton("Save");
	   saveBut.addActionListener(saveListener);
	   
	   undoBut = new JButton("Undo");
	   undoBut.addActionListener(undoListener);
	   
	   redoBut = new JButton("Redo");
	   redoBut.addActionListener(redoListener);
	   
	   panel1.add(saveBut);
	   panel1.add(undoBut);
	   panel1.add(redoBut);
	   
	   // Add panel to the frame that shows on screen
	   
	   this.add(panel1);
	   
	   this.setVisible(true);
	   
   }
   
   class ButtonListener implements ActionListener {

		public void actionPerformed(ActionEvent e) {
			
			if(e.getSource() == saveBut){
				
				// Get text in JTextArea
				
				String textInTextArea = theArticle.getText();
				
				// Set the value for the current memento
				
				originator.set(textInTextArea);
				
				// Add new article to the ArrayList
				
				caretaker.addMemento( originator.storeInMemento() );
				
				// saveFiles monitors how many articles are saved
				// currentArticle monitors the current article displayed
				
				saveFiles++;
				currentArticle++;
				
				System.out.println("Save Files " + saveFiles);
				
				// Make undo clickable
				
				undoBut.setEnabled(true);
				
			} else 
				
				if(e.getSource() == undoBut){
					
					if(currentArticle >= 1){
						
						// Decrement to the current article displayed
						
						currentArticle--;
						
						// Get the older article saved and display it in JTextArea
					
						String textBoxString = originator.restoreFromMemento( caretaker.getMemento(currentArticle) );
						
						theArticle.setText(textBoxString);
						
						// Make Redo clickable
						
						redoBut.setEnabled(true);
					
					} else {
						
						// Don't allow user to click Undo
						
						undoBut.setEnabled(false);
						
					}
					
				} else
					
					if(e.getSource() == redoBut){
					
					if((saveFiles - 1) > currentArticle){
						
						// Increment to the current article displayed
						
						currentArticle++;
						
						// Get the newer article saved and display it in JTextArea
					
						String textBoxString = originator.restoreFromMemento( caretaker.getMemento(currentArticle) );
						
						theArticle.setText(textBoxString);
						
						// Make undo clickable
						
						undoBut.setEnabled(true);
					
					} else {
						
						// Don't allow user to click Redo
						
						redoBut.setEnabled(false);
						
					}
					
				}
			
		}
		
	}
   
}

9 Responses to “Memento Design Pattern Tutorial”

  1. Tadeu says:

    We now have your memento 🙂

  2. boris says:

    i love it !

  3. eslXst says:

    Thank you, you helped me a lot!
    Don’t you think to publish a book about Design patterns?
    Do you have some JavaEE tutorial?

    I wish if I’ll have a teacher like you in my class.

    Cordially.

    • Derek Banas says:

      You’re are very welcome 🙂 The pleasure is all mine. It is very gratifying to be able to help others for me. I don’t think I’d ever publish a book just because I feel I can access the whole world online. I don’t have any interest in the money I might make.

      I have not yet covered J2EE. I decided to cover Android in depth instead, but I definitely will cover that topic. I’ll be here as long as possible to teach.

      • eslXst says:

        “I don’t think I’d ever publish a book just because I feel I can access the whole world online.”
        Thank you again 🙂

        I have a question if you don’t mind;
        I was looking on the net about the difference between Library, API and SDK?, but I couldn’t find a clear answer.

        Would you please help me to make the difference?
        if it’s possible, I would like some examples.

        Thank you for your answer 🙂
        Cordially.

        • Derek Banas says:

          A Software Development Kit (SDK) contains a bunch of tools that make it easy to create applications. Very often they contain a bunch of classes that rely on a bunch of hidden classes that simplify normally very complicated tasks.

          An Application Programming Interface (API) specification provides an easy way to bounce around and learn about all the classes that are available for you to use.

          A library, or package is just a bunch of classes that can be imported into your code for use.

          I hope that helps
          Derek

Trackbacks/Pingbacks

  1. Design Patterns Cheat Sheet by Richard Sumilang - […] Memento Design Pattern: Useful for saving history states of an object. The object stored in state is referred to as…

Leave a Reply

Your email address will not be published.

Google+