DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Writing DTOs With Java8, Lombok, and Java14+
  • Redefining Java Object Equality
  • Addressing Memory Issues and Optimizing Code for Efficiency: Glide Case
  • Singleton: 6 Ways To Write and Use in Java Programming

Trending

  • The Future of Java and AI: Coding in 2025
  • Monolith: The Good, The Bad and The Ugly
  • How To Introduce a New API Quickly Using Quarkus and ChatGPT
  • Build a Simple REST API Using Python Flask and SQLite (With Tests)
  1. DZone
  2. Coding
  3. Languages
  4. Memento Pattern Tutorial with Java Examples

Memento Pattern Tutorial with Java Examples

Learn the Memento Design Pattern with easy Java source code examples as James Sugrue continues his design patterns tutorial series, Design Patterns Uncovered

By 
James Sugrue user avatar
James Sugrue
DZone Core CORE ·
Apr. 21, 10 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
62.7K Views

Join the DZone community and get the full member experience.

Join For Free

Today's pattern is the Memento pattern which is used in undo frameworks to bring an object back to a previous state.

Memento in the Real World 

In the real world, memento's are used a reminder or reference of how something should look. For example, if you decide to take a phone apart in order to replace an internal part, you may have an identical phone available that you use as a reference, ensuring you can take get the phone back to it's original state.

Design Patterns Refcard
For a great overview of the most popular design patterns, DZone's Design Patterns Refcard is the best place to start. 

The Memento Pattern

The Memento pattern is known as abehavioural pattern, as it's used to manage algorithms, relationships and responsibilities between objects.. Thedefinition of Memento as provided in the original Gang of Four book on DesignPatterns states: 

Captures and externalizes an object's internal state so that it can be restored later, all without violating encapsulation.

The following diagram shows how the memento pattern is modelled.


Let's take a look at each of the participants in this pattern. The Originator is the object that knows how to save itself: the class that you want to make stateful. The Caretaker is that object that deals with when, and why, the Originator needs to save or restore itself. The Memento holds the information about the Originator's state, and cannot be modified by the Caretaker.

The flow of events is that the Caretaker asks the Originator for the Memento object and performs any actions that it needs to. To rollback the state before these actions, it returns the memento object to the originator. 

When Would I Use This Pattern?

The Memento pattern is useful when you need to provide an undo mechanism in your applications, when the internal state of an object may need to be restored at a later stage. Using serialization along with this pattern, it's easy to preserve the object state and bring it back later on.

So How Does It Work In Java?

Let's use a simple example in Java to illustrate this pattern.As it's a pattern used for undo frameworks, we'll model a editor. 

First, the memento needs to be able to save editor contents, which will just be plain text: 

//Memento
public class EditorMemento {
  private final String editorState;
  public EditorMemento(String state) {
    editorState = state;
  }
  public String getSavedState() {
    return editorState;
  }
}

 

Now our Originator class, the editor, can use the memento:

//Originator
public class Editor {
  //state
  public String editorContents;
  public void setState(String contents) {
    this.editorContents = contents;
  }
  public EditorMemento save() {
    return new EditorMemento(editorContents);
  }
  public void restoreToState(EditorMemento memento) {
    editorContents = memento.getSavedState();
  }
}

Anytime we want to save the state, we call the save() method, and an undo would call the restoreToState method.
Our caretaker can then keep track of all the memento's in a stack for the undo framework to work.

Watch Out for the Downsides

Some problems with this pattern is that the saving or restoring of state can be a time consuming process. Used incorrectly, it can expose the internal structure of your object, thus allowing any other object to change the state of your object.

Next Up

As we start to near the end of the series, we'll look at the Mediator pattern next.

Enjoy the Whole "Design Patterns Uncovered" Series:

Creational Patterns

  • Learn The Abstract Factory Pattern
  • Learn The Builder Pattern
  • Learn The Factory Method Pattern
  • Learn The Prototype Pattern

Structural Patterns

  • Learn The Adapter Pattern
  • Learn The Bridge Pattern
  • Learn The Decorator Pattern
  • Learn The Facade Pattern
  • Learn The Proxy Pattern

Behavioral Patterns

  • Learn The Chain of Responsibility Pattern
  • Learn The Command Pattern
  • Learn The Interpreter Pattern
  • Learn The Iterator Pattern
  • Learn The Mediator Pattern
  • Learn The Memento Pattern
  • Learn The Observer Pattern
  • Learn The State Pattern
  • Learn The Strategy Pattern
  • Learn The Template Method Pattern
  • Learn The Visitor Pattern
Memento pattern Java (programming language) Object (computer science)

Opinions expressed by DZone contributors are their own.

Related

  • Writing DTOs With Java8, Lombok, and Java14+
  • Redefining Java Object Equality
  • Addressing Memory Issues and Optimizing Code for Efficiency: Glide Case
  • Singleton: 6 Ways To Write and Use in Java Programming

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!