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.
Join the DZone community and get the full member experience.
Join For FreeToday, 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.
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:
package org.trishinfotech.memento;
public class Employee {
protected int empId;
protected String name;
protected String designation;
protected long salary;
protected String department;
protected String project;
public Employee(int empId) {
super();
this.empId = empId;
}
public int getEmpId() {
return empId;
}
public String getName() {
return name;
}
public Employee setName(String name) {
this.name = name;
return this;
}
public String getDesignation() {
return designation;
}
public Employee setDesignation(String designation) {
this.designation = designation;
return this;
}
public long getSalary() {
return salary;
}
public Employee setSalary(long salary) {
this.salary = salary;
return this;
}
public String getDepartment() {
return department;
}
public Employee setDepartment(String department) {
this.department = department;
return this;
}
public String getProject() {
return project;
}
public Employee setProject(String project) {
this.project = project;
return this;
}
public String toString() {
return "Employee [empId=" + empId + ", name=" + name + ", designation=" + designation + ", salary=" + salary
+ ", department=" + department + ", project=" + project + "]";
}
public EmployeeMemento createMemento() {
return new EmployeeMemento(empId, name, designation, salary, department, project);
}
public void restore(EmployeeMemento memento) {
if (memento != null) {
this.empId = memento.empId;
this.name = memento.name;
this.designation = memento.designation;
this.salary = memento.salary;
this.department = memento.department;
this.project = memento.project;
} else {
System.err.println("Can't restore without memento object!");
}
}
}
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:
xxxxxxxxxx
package org.trishinfotech.memento;
public class EmployeeMemento {
protected int empId;
protected String name;
protected String designation;
protected long salary;
protected String department;
protected String project;
public EmployeeMemento(int empId, String name, String designation, long salary, String department, String project) {
super();
this.empId = empId;
this.name = name;
this.designation = designation;
this.salary = salary;
this.department = department;
this.project = project;
}
public int getEmpId() {
return empId;
}
public String getName() {
return name;
}
public String getDesignation() {
return designation;
}
public long getSalary() {
return salary;
}
public String getDepartment() {
return department;
}
public String getProject() {
return project;
}
public String toString() {
return "EmployeeMemento [empId=" + empId + ", name=" + name + ", designation=" + designation + ", salary="
+ salary + ", department=" + department + ", project=" + project + "]";
}
}
Now code for EmployeeCaretaker class:
xxxxxxxxxx
package org.trishinfotech.memento;
import java.util.HashMap;
import java.util.Map;
public class EmployeeCaretaker {
protected Map<Integer, Map<String, EmployeeMemento>> mementoHistory = new HashMap<Integer, Map<String, EmployeeMemento>>();
public void addMemento(int empId, String mementoMessage, EmployeeMemento memento) {
if (mementoMessage != null && mementoMessage.trim().length() != 0 && memento != null) {
Map<String, EmployeeMemento> mementoMessageMap = mementoHistory.get(empId);
if (mementoMessageMap == null) {
mementoMessageMap = new HashMap<String, EmployeeMemento>();
mementoHistory.put(empId, mementoMessageMap);
}
mementoMessageMap.put(mementoMessage, memento);
System.out.printf("Snapshot of employee name '%s' stored with message '%s'.\n", memento.getName(),
mementoMessage);
}
}
public EmployeeMemento getMemento(int empId, String mementoMessage) {
EmployeeMemento memento = null;
if (mementoMessage != null && mementoMessage.trim().length() != 0) {
Map<String, EmployeeMemento> mementoMessageMap = mementoHistory.get(empId);
if (mementoMessageMap != null) {
memento = mementoMessageMap.get(mementoMessage);
if (memento != null) {
System.out.printf("Snapshot of employee name '%s' with message '%s' restored\n", memento.getName(),
mementoMessage);
} else {
System.err.println("Not able to find the memento!");
}
}
}
return memento;
}
public void printStoredMementoObjects() {
System.out.println("======================================================");
mementoHistory.forEach((empId, mementoMessageMap) -> {
mementoMessageMap.forEach((message, memento) -> {
System.out.printf("EmpId: '%d', Message: '%s', Memento: '%s'\n", empId, message, memento);
});
});
System.out.println("======================================================");
}
}
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:
xxxxxxxxxx
package org.trishinfotech.memento;
public class Main {
public static void main(String[] args) {
EmployeeCaretaker caretaker = new EmployeeCaretaker();
System.out.println("creating employee objects with intial values");
Employee racheal = new Employee(100).setName("Racheal").setDesignation("Lead").setSalary(100000).setDepartment("R&D").setProject("Transportation Management");
Employee micheal = new Employee(101).setName("Micheal").setDesignation("Developer").setSalary(75000).setDepartment("Engineering").setProject("IoT");
System.out.println(racheal);
System.out.println(micheal);
EmployeeMemento rachealMemento = racheal.createMemento();
EmployeeMemento michealMemento = micheal.createMemento();
caretaker.addMemento(racheal.getEmpId(), "Saved at intitial stage", rachealMemento);
caretaker.addMemento(micheal.getEmpId(), "Saved at intitial stage", michealMemento);
System.out.println("\nracheal got promotion");
racheal.setDesignation("Manager").setSalary(120000);
System.out.println("micheal assigned to another project.");
micheal.setProject("Android App");
System.out.println(racheal);
System.out.println(micheal);
rachealMemento = racheal.createMemento();
michealMemento = micheal.createMemento();
caretaker.addMemento(racheal.getEmpId(), "Saved at promotion", rachealMemento);
caretaker.addMemento(micheal.getEmpId(), "Saved at android project", michealMemento);
System.out.println("\nracheal got increment");
racheal.setSalary(140000);
System.out.println("micheal got promotion");
micheal.setDesignation("Lead Developer").setSalary(90000);
System.out.println(racheal);
System.out.println(micheal);
rachealMemento = racheal.createMemento();
michealMemento = micheal.createMemento();
caretaker.addMemento(racheal.getEmpId(), "Saved at increment", rachealMemento);
caretaker.addMemento(micheal.getEmpId(), "Saved at promotion", michealMemento);
System.out.println("\nLet's print the stored memento objects we have");
caretaker.printStoredMementoObjects();
System.out.println("\nnow for some reason, we like to revert racheal to initial stage.");
System.out.println("and micheal to android project.");
rachealMemento = caretaker.getMemento(racheal.getEmpId(), "Saved at intitial stage");
michealMemento = caretaker.getMemento(micheal.getEmpId(), "Saved at android project");
racheal.restore(rachealMemento);
micheal.restore(michealMemento);
System.out.println(racheal);
System.out.println(micheal);
}
}
And the below is the the output:
xxxxxxxxxx
creating employee objects with intial values
Employee [empId=100, name=Racheal, designation=Lead, salary=100000, department=R&D, project=Transportation Management]
Employee [empId=101, name=Micheal, designation=Developer, salary=75000, department=Engineering, project=IoT]
Snapshot of employee name 'Racheal' stored with message 'Saved at intitial stage'.
Snapshot of employee name 'Micheal' stored with message 'Saved at intitial stage'.
racheal got promotion
micheal assigned to another project.
Employee [empId=100, name=Racheal, designation=Manager, salary=120000, department=R&D, project=Transportation Management]
Employee [empId=101, name=Micheal, designation=Developer, salary=75000, department=Engineering, project=Android App]
Snapshot of employee name 'Racheal' stored with message 'Saved at promotion'.
Snapshot of employee name 'Micheal' stored with message 'Saved at android project'.
racheal got increment
micheal got promotion
Employee [empId=100, name=Racheal, designation=Manager, salary=140000, department=R&D, project=Transportation Management]
Employee [empId=101, name=Micheal, designation=Lead Developer, salary=90000, department=Engineering, project=Android App]
Snapshot of employee name 'Racheal' stored with message 'Saved at increment'.
Snapshot of employee name 'Micheal' stored with message 'Saved at promotion'.
Let's print the stored memento objects we have
======================================================
EmpId: '100', Message: 'Saved at increment', Memento: 'EmployeeMemento [empId=100, name=Racheal, designation=Manager, salary=140000, department=R&D, project=Transportation Management]'
EmpId: '100', Message: 'Saved at intitial stage', Memento: 'EmployeeMemento [empId=100, name=Racheal, designation=Lead, salary=100000, department=R&D, project=Transportation Management]'
EmpId: '100', Message: 'Saved at promotion', Memento: 'EmployeeMemento [empId=100, name=Racheal, designation=Manager, salary=120000, department=R&D, project=Transportation Management]'
EmpId: '101', Message: 'Saved at intitial stage', Memento: 'EmployeeMemento [empId=101, name=Micheal, designation=Developer, salary=75000, department=Engineering, project=IoT]'
EmpId: '101', Message: 'Saved at android project', Memento: 'EmployeeMemento [empId=101, name=Micheal, designation=Developer, salary=75000, department=Engineering, project=Android App]'
EmpId: '101', Message: 'Saved at promotion', Memento: 'EmployeeMemento [empId=101, name=Micheal, designation=Lead Developer, salary=90000, department=Engineering, project=Android App]'
======================================================
now for some reason, we like to revert racheal to initial stage.
and micheal to android project.
Snapshot of employee name 'Racheal' with message 'Saved at intitial stage' restored
Snapshot of employee name 'Micheal' with message 'Saved at android project' restored
Employee [empId=100, name=Racheal, designation=Lead, salary=100000, department=R&D, project=Transportation Management]
Employee [empId=101, name=Micheal, designation=Developer, salary=75000, department=Engineering, project=Android App]
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!
Opinions expressed by DZone contributors are their own.
Comments