
Java programmer expert
Today we will look at another Java design pattern from the category of behavioural patterns – Memento. Design patterns in this category deal with the interaction between objects and their responsibility.
The Memento pattern allows the internal state of an object to be preserved without violating the encapsulation principle, which can be restored if necessary, thus returning the object to its original state.
In applications, it is quite common to save the state that the user has entered as input to the program, e.g. when filling out a web form. If the internet connection is lost, it is useful to be able to restore the last state of the data entered without having to ask the user again.
In similar situations, where we need to store intermediate states and easily return to them at any time, the Memento design pattern is used, the principle of which is to decouple the storage of the object state from the object itself. The object that needs to store its state creates a Memento object that contains the necessary state information. This Memento object can then be stored (e.g. in history) and used later to restore the object to its original state.
A well-designed object is encapsulated, i.e. the object’s data is hidden inside the object and not accessible from outside, so the object itself – the Originator – is responsible for storing the internal state in the (Memento) object and restoring it from the (Memento) object. The client (Caretaker) takes the Memento object from the Originator object when the state is saved and returns it to the Originator object when it is restored. This method allows the internal state of the Originator object to be saved and restored without breaking its encapsulation.
We demonstrate how the Memento design pattern can be used to save and restore the state of an object without violating the encapsulation principle by playing a simple game in which the player traverses increasingly dangerous levels, where they may suffer an injury at each step, and where they can save the game state at any time and restore it on demand.
Game.java
package designpatterns;
public class Hra {
private int levelId;
private int zdravie;
public Hra() {
spustitHru();
}
public void spustitHru() {
this.levelId = 1;
this.zdravie = 100;
System.out.println("Spúšťam novú hru.");
ukazStavHry();
}
public Memento ulozitHru() {
System.out.println("Ukladám stav hry.");
return new Memento(levelId, zdravie);
}
public void nacitatHru(Memento memento) {
System.out.println("Načítavam uloženú pozíciu v hre.");
this.levelId = memento.getLevelId();
this.zdravie = memento.getZdravie();
}
public void dokoncitLevel() {
levelId++;
System.out.println("Pokračujem do levelu " + levelId);
ukazStavHry();
}
public void zranitSa(int poskodenie) {
this.zdravie -= poskodenie;
System.out.println("Hráč utrpel zranenie (" + -poskodenie + ")");
ukazStavHry();
if (zdravie <= 0) {
System.out.println("Hráč stratil celé zdravie. Hra začne od začiatku.");
spustitHru();
}
}
public void ukazStavHry() {
System.out.println(" Level " + levelId + ", Zdravie: " + zdravie);
}
}
The Game class contains methods for starting, saving and loading a game, completing a level, injuring a player and displaying the state of the game.
Memento.java
package designpatterns;
public class Memento {
private int levelId;
private int zdravie;
public Memento(int levelId, int zdravie) {
this.levelId = levelId;
this.zdravie = zdravie;
}
public int getLevelId() {
return levelId;
}
public int getZdravie() {
return zdravie;
}
}
The Memento class serves as an object that stores the state of the game. Memento contains information about level (levelId) and health (health).
Playing.java
import designpatterns.Hra;
import designpatterns.Memento;
public class Hranie {
public static void main(String[] args) {
Hra hra = new Hra();
hra.zranitSa(12);
hra.dokoncitLevel();
Memento ulozenaPozicia = hra.ulozitHru();
hra.zranitSa(24);
hra.zranitSa(18);
hra.dokoncitLevel();
hra.zranitSa(20);
hra.zranitSa(12);
hra.zranitSa(14);
hra.nacitatHru(ulozenaPozicia);
hra.ukazStavHry();
}
}
The Playing class contains a main method that demonstrates the use of the Memento design pattern. The player starts the game, gets injured, completes the level, saves the game state (Memento), gets injured again, completes another level, gets injured again and, to avoid having to start the game from the beginning, finally resumes the game from the saved position.
The output of this example is:
The Memento pattern is a design pattern that solves the problem of storing and restoring the state of an object so that it can return to a previous state. It is often used to implement an undo/rollback mechanism or to keep a history of object states.
We have prepared the files with the above example in the form of code that you can run directly in Java. You can download the Java Memento code here.
If you’re a Java developer looking for work, check out our employee benefits and respond to our job offers!