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

  • Object Relational Behavioral Design Patterns in Java
  • Distribution Design Patterns in Java - Data Transfer Object (DTO) And Remote Facade Design Patterns
  • Context Object Design Pattern in Java: Introduction and Key Points
  • Java: Object Pool Design Pattern

Trending

  • Infrastructure as Code (IaC) Beyond the Basics
  • Operational Principles, Architecture, Benefits, and Limitations of Artificial Intelligence Large Language Models
  • Building Reliable LLM-Powered Microservices With Kubernetes on AWS
  • The Full-Stack Developer's Blind Spot: Why Data Cleansing Shouldn't Be an Afterthought
  1. DZone
  2. Coding
  3. Languages
  4. Memento Design Pattern In Java

Memento Design Pattern In Java

Another behavioral design pattern called the Memento Design Pattern which is used to restore the state of an object to a previous state.

By 
Brijesh Saxena user avatar
Brijesh Saxena
DZone Core CORE ·
Updated Nov. 05, 20 · Tutorial
Likes (8)
Comment
Save
Tweet
Share
14.4K Views

Join the DZone community and get the full member experience.

Join For Free

Today, I would like to discuss another behavioral design pattern called the Memento Design Pattern which is used to restore the state of an object to a previous state.

Memento Design Pattern

  • The Memento Design Pattern is one of the twenty-three well-known GoF design patterns that provide the ability to restore an object to its previous state.
  • The Memento Design Pattern is implemented with the help of three objects: the originator, a caretaker, and a memento. 
    • Originator — The object whose internal state we like to store. The Originator object creates a memento object to store its internal state. So, the Originator object knows how to save and restore itself. The object which gets and sets the values of Memento objects.
    • Caretaker — The object which knows why and when the Originator needs to save and restore itself. The object operates on the Originator while having the possibility to rollback. It maintains the history of the Memento objects created. The caretaker takes a snapshot of Originator before operating.
    • Memento — The POJO object that contains basic state storage and retrieval capabilities.  The Memento object is immutable in general. The object holds the internal state of the Originator and allows it to restore it.
  • The classic example of the Memento Pattern is a pseudorandom number generator or finite state machine.
  • Git stashing is another example of the Memento Design Pattern.
  • The internal state of the Originator object should be saved externally so that the object can be restored to this state later. Also, the object's encapsulation must not be violated.
  •  The caretaker requests a Memento from Originator before operating. And use that Memento to restore the Originator to its previous state if needed.
  • We can make Memento Design Pattern implementation more generic by using Serialization; that will eliminate the requirement of every class having its own Memento class.
  • The Memento Design Pattern can also be used with the Command Design Pattern for achieving undo of the commands.

mementodesign

To understand the Memento Design Pattern let's take the example of the Employee class storing and retrieving its state using EmployeeMemento class.

Employee Class Storing State Using Memento Design Pattern

 Code for Employee class:

Java
 




x
89


 
1
package org.trishinfotech.memento;
2
 
          
3
public class Employee {
4
 
          
5
    protected int empId;
6
    protected String name;
7
    protected String designation;
8
    protected long salary;
9
    protected String department;
10
    protected String project;
11
 
          
12
    public Employee(int empId) {
13
        super();
14
        this.empId = empId;
15
    }
16
 
          
17
    public int getEmpId() {
18
        return empId;
19
    }
20
 
          
21
    public String getName() {
22
        return name;
23
    }
24
 
          
25
    public Employee setName(String name) {
26
        this.name = name;
27
        return this;
28
    }
29
 
          
30
    public String getDesignation() {
31
        return designation;
32
    }
33
 
          
34
    public Employee setDesignation(String designation) {
35
        this.designation = designation;
36
        return this;
37
    }
38
 
          
39
    public long getSalary() {
40
        return salary;
41
    }
42
 
          
43
    public Employee setSalary(long salary) {
44
        this.salary = salary;
45
        return this;
46
    }
47
 
          
48
    public String getDepartment() {
49
        return department;
50
    }
51
 
          
52
    public Employee setDepartment(String department) {
53
        this.department = department;
54
        return this;
55
    }
56
 
          
57
    public String getProject() {
58
        return project;
59
    }
60
 
          
61
    public Employee setProject(String project) {
62
        this.project = project;
63
        return this;
64
    }
65
 
          
66
    @Override
67
    public String toString() {
68
        return "Employee [empId=" + empId + ", name=" + name + ", designation=" + designation + ", salary=" + salary
69
                + ", department=" + department + ", project=" + project + "]";
70
    }
71
 
          
72
    public EmployeeMemento createMemento() {
73
        return new EmployeeMemento(empId, name, designation, salary, department, project);
74
    }
75
 
          
76
    public void restore(EmployeeMemento memento) {
77
        if (memento != null) {
78
            this.empId = memento.empId;
79
            this.name = memento.name;
80
            this.designation = memento.designation;
81
            this.salary = memento.salary;
82
            this.department = memento.department;
83
            this.project = memento.project;
84
        } else {
85
            System.err.println("Can't restore without memento object!");
86
        }
87
    }
88
}
89
 
          



Here we can see that the originator Employee class creates and restores EmployeeMemento. Also as you can see, I made EmpId to be set only while creating Employee object and I like to keep EmpId unique as well.

Code for EmployeeMemento class:

Java
 




xxxxxxxxxx
1
53


 
1
package org.trishinfotech.memento;
2
 
          
3
public class EmployeeMemento {
4
 
          
5
    protected int empId;
6
    protected String name;
7
    protected String designation;
8
    protected long salary;
9
    protected String department;
10
    protected String project;
11
 
          
12
    public EmployeeMemento(int empId, String name, String designation, long salary, String department, String project) {
13
        super();
14
        this.empId = empId;
15
        this.name = name;
16
        this.designation = designation;
17
        this.salary = salary;
18
        this.department = department;
19
        this.project = project;
20
    }
21
 
          
22
    public int getEmpId() {
23
        return empId;
24
    }
25
 
          
26
    public String getName() {
27
        return name;
28
    }
29
 
          
30
    public String getDesignation() {
31
        return designation;
32
    }
33
 
          
34
    public long getSalary() {
35
        return salary;
36
    }
37
 
          
38
    public String getDepartment() {
39
        return department;
40
    }
41
 
          
42
    public String getProject() {
43
        return project;
44
    }
45
 
          
46
    @Override
47
    public String toString() {
48
        return "EmployeeMemento [empId=" + empId + ", name=" + name + ", designation=" + designation + ", salary="
49
                + salary + ", department=" + department + ", project=" + project + "]";
50
    }
51
 
          
52
}
53
 
          



Now code for EmployeeCaretaker class:

Java
 




xxxxxxxxxx
1
51


 
1
package org.trishinfotech.memento;
2
 
          
3
import java.util.HashMap;
4
import java.util.Map;
5
 
          
6
public class EmployeeCaretaker {
7
 
          
8
    protected Map<Integer, Map<String, EmployeeMemento>> mementoHistory = new HashMap<Integer, Map<String, EmployeeMemento>>();
9
 
          
10
    public void addMemento(int empId, String mementoMessage, EmployeeMemento memento) {
11
        if (mementoMessage != null && mementoMessage.trim().length() != 0 && memento != null) {
12
            Map<String, EmployeeMemento> mementoMessageMap = mementoHistory.get(empId);
13
            if (mementoMessageMap == null) {
14
                mementoMessageMap = new HashMap<String, EmployeeMemento>();
15
                mementoHistory.put(empId, mementoMessageMap);
16
            }
17
            mementoMessageMap.put(mementoMessage, memento);
18
            System.out.printf("Snapshot of employee name '%s' stored with message '%s'.\n", memento.getName(),
19
                    mementoMessage);
20
        }
21
    }
22
 
          
23
    public EmployeeMemento getMemento(int empId, String mementoMessage) {
24
        EmployeeMemento memento = null;
25
        if (mementoMessage != null && mementoMessage.trim().length() != 0) {
26
            Map<String, EmployeeMemento> mementoMessageMap = mementoHistory.get(empId);
27
            if (mementoMessageMap != null) {
28
                memento = mementoMessageMap.get(mementoMessage);
29
                if (memento != null) {
30
                    System.out.printf("Snapshot of employee name '%s' with message '%s' restored\n", memento.getName(),
31
                            mementoMessage);
32
                } else {
33
                    System.err.println("Not able to find the memento!");
34
                }
35
            }
36
        }
37
        return memento;
38
    }
39
 
          
40
    public void printStoredMementoObjects() {
41
        System.out.println("======================================================");
42
        mementoHistory.forEach((empId, mementoMessageMap) -> {
43
            mementoMessageMap.forEach((message, memento) -> {
44
                System.out.printf("EmpId: '%d', Message: '%s', Memento: '%s'\n", empId, message, memento);
45
            });
46
        });
47
        System.out.println("======================================================");
48
    }
49
 
          
50
}
51
 
          



I am using EmpId and the Message String as key while storing Memento. The same I will use while restoring the Employee using Memento. 

Now, its time to write Main class to execute and test the output:

Java
 




xxxxxxxxxx
1
49


 
1
package org.trishinfotech.memento;
2
 
          
3
public class Main {
4
 
          
5
    public static void main(String[] args) {
6
        EmployeeCaretaker caretaker = new EmployeeCaretaker();
7
        System.out.println("creating employee objects with intial values");
8
        Employee racheal = new Employee(100).setName("Racheal").setDesignation("Lead").setSalary(100000).setDepartment("R&D").setProject("Transportation Management");
9
        Employee micheal = new Employee(101).setName("Micheal").setDesignation("Developer").setSalary(75000).setDepartment("Engineering").setProject("IoT");
10
        System.out.println(racheal);
11
        System.out.println(micheal);
12
        EmployeeMemento rachealMemento = racheal.createMemento();
13
        EmployeeMemento michealMemento = micheal.createMemento();
14
        caretaker.addMemento(racheal.getEmpId(), "Saved at intitial stage", rachealMemento);
15
        caretaker.addMemento(micheal.getEmpId(), "Saved at intitial stage", michealMemento);
16
        System.out.println("\nracheal got promotion");
17
        racheal.setDesignation("Manager").setSalary(120000);
18
        System.out.println("micheal assigned to another project.");
19
        micheal.setProject("Android App");
20
        System.out.println(racheal);
21
        System.out.println(micheal);
22
        rachealMemento = racheal.createMemento();
23
        michealMemento = micheal.createMemento();
24
        caretaker.addMemento(racheal.getEmpId(), "Saved at promotion", rachealMemento);
25
        caretaker.addMemento(micheal.getEmpId(), "Saved at android project", michealMemento);
26
        System.out.println("\nracheal got increment");
27
        racheal.setSalary(140000);
28
        System.out.println("micheal got promotion");
29
        micheal.setDesignation("Lead Developer").setSalary(90000);
30
        System.out.println(racheal);
31
        System.out.println(micheal);
32
        rachealMemento = racheal.createMemento();
33
        michealMemento = micheal.createMemento();
34
        caretaker.addMemento(racheal.getEmpId(), "Saved at increment", rachealMemento);
35
        caretaker.addMemento(micheal.getEmpId(), "Saved at promotion", michealMemento);
36
        System.out.println("\nLet's print the stored memento objects we have");
37
        caretaker.printStoredMementoObjects();
38
        System.out.println("\nnow for some reason, we like to revert racheal to initial stage.");
39
        System.out.println("and micheal to android project.");
40
        rachealMemento = caretaker.getMemento(racheal.getEmpId(), "Saved at intitial stage");
41
        michealMemento = caretaker.getMemento(micheal.getEmpId(), "Saved at android project");
42
        racheal.restore(rachealMemento);
43
        micheal.restore(michealMemento);
44
        System.out.println(racheal);
45
        System.out.println(micheal);
46
    }
47
 
          
48
}
49
 
          



And the below is the the output:

Java
 




xxxxxxxxxx
1
37


 
1
creating employee objects with intial values
2
Employee [empId=100, name=Racheal, designation=Lead, salary=100000, department=R&D, project=Transportation Management]
3
Employee [empId=101, name=Micheal, designation=Developer, salary=75000, department=Engineering, project=IoT]
4
Snapshot of employee name 'Racheal' stored with message 'Saved at intitial stage'.
5
Snapshot of employee name 'Micheal' stored with message 'Saved at intitial stage'.
6
 
          
7
racheal got promotion
8
micheal assigned to another project.
9
Employee [empId=100, name=Racheal, designation=Manager, salary=120000, department=R&D, project=Transportation Management]
10
Employee [empId=101, name=Micheal, designation=Developer, salary=75000, department=Engineering, project=Android App]
11
Snapshot of employee name 'Racheal' stored with message 'Saved at promotion'.
12
Snapshot of employee name 'Micheal' stored with message 'Saved at android project'.
13
 
          
14
racheal got increment
15
micheal got promotion
16
Employee [empId=100, name=Racheal, designation=Manager, salary=140000, department=R&D, project=Transportation Management]
17
Employee [empId=101, name=Micheal, designation=Lead Developer, salary=90000, department=Engineering, project=Android App]
18
Snapshot of employee name 'Racheal' stored with message 'Saved at increment'.
19
Snapshot of employee name 'Micheal' stored with message 'Saved at promotion'.
20
 
          
21
Let's print the stored memento objects we have
22
======================================================
23
EmpId: '100', Message: 'Saved at increment', Memento: 'EmployeeMemento [empId=100, name=Racheal, designation=Manager, salary=140000, department=R&D, project=Transportation Management]'
24
EmpId: '100', Message: 'Saved at intitial stage', Memento: 'EmployeeMemento [empId=100, name=Racheal, designation=Lead, salary=100000, department=R&D, project=Transportation Management]'
25
EmpId: '100', Message: 'Saved at promotion', Memento: 'EmployeeMemento [empId=100, name=Racheal, designation=Manager, salary=120000, department=R&D, project=Transportation Management]'
26
EmpId: '101', Message: 'Saved at intitial stage', Memento: 'EmployeeMemento [empId=101, name=Micheal, designation=Developer, salary=75000, department=Engineering, project=IoT]'
27
EmpId: '101', Message: 'Saved at android project', Memento: 'EmployeeMemento [empId=101, name=Micheal, designation=Developer, salary=75000, department=Engineering, project=Android App]'
28
EmpId: '101', Message: 'Saved at promotion', Memento: 'EmployeeMemento [empId=101, name=Micheal, designation=Lead Developer, salary=90000, department=Engineering, project=Android App]'
29
======================================================
30
 
          
31
now for some reason, we like to revert racheal to initial stage.
32
and micheal to android project.
33
Snapshot of employee name 'Racheal' with message 'Saved at intitial stage' restored
34
Snapshot of employee name 'Micheal' with message 'Saved at android project' restored
35
Employee [empId=100, name=Racheal, designation=Lead, salary=100000, department=R&D, project=Transportation Management]
36
Employee [empId=101, name=Micheal, designation=Developer, salary=75000, department=Engineering, project=Android App]
37
 
          



I hope by the example, we get a fair idea about the implementation of the Memento Design Pattern.

Source Code can be found here: Memento-Design-Pattern-Sample-Code

Liked the article? Please don't forget to press that like button. Happy coding!

Design Java (programming language) Object (computer science)

Opinions expressed by DZone contributors are their own.

Related

  • Object Relational Behavioral Design Patterns in Java
  • Distribution Design Patterns in Java - Data Transfer Object (DTO) And Remote Facade Design Patterns
  • Context Object Design Pattern in Java: Introduction and Key Points
  • Java: Object Pool Design Pattern

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!