Memento Design Pattern in Java
This tutorial explains Gang of Four's Memento design pattern in Java. It starts with explaining the Memento pattern's definition, followed by the two mandatory requirements which must be met for applying the pattern. Next, it shows the UML class diagram for Memento pattern and explains the roles of the various constituent classes of the pattern. An example use case showing Memento pattern implementation is then explained using its class diagram, Java code for implementation and detailed explained of the code.
Introduction Memento Design Pattern is a behavioral design pattern among the Gang Of Four(GOF)Article on GOF Patterns & their types Design Patterns. Being a behavioral design pattern, the memento pattern basically deals with how the objects communicate and share responsibilities among each other. What is Memento Design Pattern Memento design pattern provides ability to capture(save) an object's state and then restore back this captured state when required by the system.
Memento design pattern can be chosen when the following 2 requirements occur in conjunction -
This separation of concerns between the actual system state and the memento implementation allows for single responsibility principleClick to Read tutorial on Single Responsibility Principle being effectively applied. This is because the responsibility of handling the system's state is separated from the state capture and restoring responsibility.
Class Diagram for Memento Design Pattern
Explanation of Memento Design Pattern's Class Diagram
OUTPUT on running the
Explanation of Java Example's Class Diagram & Code
The Java class diagram above depicts Memento pattern implemented for a game which needs to keep track of player points & player level as the game is being played -
Introduction Memento Design Pattern is a behavioral design pattern among the Gang Of Four(GOF)Article on GOF Patterns & their types Design Patterns. Being a behavioral design pattern, the memento pattern basically deals with how the objects communicate and share responsibilities among each other. What is Memento Design Pattern Memento design pattern provides ability to capture(save) an object's state and then restore back this captured state when required by the system.
Memento design pattern can be chosen when the following 2 requirements occur in conjunction -
- The state of an object in the system needs to be captured/saved so that the object can be restored to that state later.
- Direct access to object's state is not an option as that would break the encapsulation of object by exposing its internal structure.
Class Diagram for Memento Design Pattern
- There are 3 main participants in the memento pattern's class diagrams -
Originator,MementoandCaretaker. Originatoris the object of which the state is to be stored. The responsibilities of storing the snapshot of its state and then restoring the state fromMementolie withOriginator. This is the reason why the methodscreateMementoFromState()(for storing the state) andsetStateFromMemento()(for restoring the state) have been defined on theOriginator.Mementostores the internal state of theOriginator. OnlyOriginatoris allowed storing to/restoring from theMementoobject. This allows the internal structure/state ofOriginatorto not be visible to other classes thus achieving the encapsulation requirement of aMementoimplementation.Caretakerholds the memento object and is responsible for its safekeeping. When a snapshot of theOriginator’s state is required then theCaretakerasks theOriginatorfor the snapshot as a memento object and stores the snapshot. When theOriginator’s state is to be restored thenCaretakerpasses theMementoobject back to theOriginator.- There is also a
Stateclass which holds the state of theOriginator.Mementoalso holds this state of theOriginator. As this is simply the representation ofOriginator’s internal state hence there is no separate class forStatedepicted in the class diagram. However, in the java example's class diagram, which is next, I have included theStateclass also.
Code for the classes shown in Java Example’s Class Diagram
//PlayerStatus.java
public class PlayerStatus{
private long playerPoints;
private int playerLevel;
public void setPlayerPoints(long playerPoints){
this.playerPoints=playerPoints;
}
public long getPlayerPoints(){
return this.playerPoints;
}
public void setPlayerLevel(int playerLevel){
this.playerLevel=playerLevel;
}
public int getPlayerLevel(){
return this.playerLevel;
}
}
//PlayerStatusMemento.java
public class PlayerStatusMemento{
private PlayerStatus playerStatus;
public void setPlayerStatus(PlayerStatus playerStatus){
this.playerStatus=playerStatus;
}
public PlayerStatus getPlayerStatus(){
return this.playerStatus ;
}
}
//CurrentPlayerStatus.java
public class CurrentPlayerStatus{
private int playerLevel=1;
private long playerPoints=0;
public void setStatusFromMemento(PlayerStatusMemento memento){
this.playerLevel=memento.getPlayerStatus(). getPlayerLevel();
this.playerPoints=memento.getPlayerStatus(). getPlayerPoints();
}
public PlayerStatusMemento createMementoFromStatus(){
PlayerStatusMemento memento=new PlayerStatusMemento();
PlayerStatus playerStatus=new PlayerStatus();
playerStatus.setPlayerLevel(this.playerLevel);
playerStatus.setPlayerPoints(this.playerPoints);
memento.setPlayerStatus(playerStatus);
return memento;
}
public void setPlayerPoints(long playerPoints){
this.playerPoints=playerPoints;
}
public long getPlayerPoints(){
return this.playerPoints;
}
public void setPlayerLevel(int playerLevel){
this.playerLevel=playerLevel;
}
public int getPlayerLevel(){
return this.playerLevel;
}
}
//PlayerStatusCaretaker.java
public class PlayerStatusCaretaker{
public static void main(String args[]){
PlayerStatusMemento playerStatusMemento;
System.out.println("Game Started");
CurrentPlayerStatus currentPlayerStatus=new CurrentPlayerStatus();
currentPlayerStatus.setPlayerPoints(1200L);
currentPlayerStatus.setPlayerLevel(2);
System.out.println("Player reached 2nd level with 1200 points");
printCurrentPlayerStatus(currentPlayerStatus);
System.out.println("Player stores current status as memento");
playerStatusMemento= currentPlayerStatus.createMementoFromStatus();
currentPlayerStatus.setPlayerPoints(2200L);
currentPlayerStatus.setPlayerLevel(4);
printCurrentPlayerStatus(currentPlayerStatus);
System.out.println("At this point player loses & is relegated to status saved in memento");
currentPlayerStatus.setStatusFromMemento(playerStatusMemento);
printCurrentPlayerStatus(currentPlayerStatus);
}
public static void printCurrentPlayerStatus(CurrentPlayerStatus currentPlayerStatus){
System.out.println("Player points->"+currentPlayerStatus.getPlayerPoints()+",level->"+currentPlayerStatus.getPlayerLevel());
}
}
PlayerStatusCaretaker.javaGame Started Player reached 2nd level with 1200 points Player points->1200,level->2 Player stores current status as memento Player points->2200,level->4 At this point player loses & is relegated to status saved in memento Player points->1200,level->2
PlayerStatusrepresents the state of the Originator(CurrentPlayerStatus). The State/PlayerStatus consists of two attributes -playerPointsandplayerLevel.PlayerStatusMementois the memento object which stores an instance ofPlayerStatuswhich is nothing but a snapshot ofCurrentPlayingStatus’s internal state.CurrentPlayerStatusis the Originator i.e the object of which we need to store/restore the internal snapshot.CurrentPlayerStatusholds its state in two attributesplayerPointsandplayerLevelwhich are the exact same attributes inPlayerStatusobject which is stored in thePlayerStatusMementoobject.PlayerStatusCaretakerin the above example drives the game and stores/restores the memento with the help of Originator. It starts the game. As the game progresses and the player reaches level 2 with 1200 points,PlayerStatusCaretakerasks theCurrentPlayerStatus(Originator) object to create a memento object and store the currentPlayerStatusby calling its methodcreateMementoFromStatus(). The player then moves to 2200 points and level 4 where he,hypothetically, loses a life and goes down to the last state stored. This is the state stored in the PlayerStatusMemento object which thePlayerStatusCaretakersets by invoking thesetStatusFromMemento(Momento)method ofCurrentPlayerStatus. The gameplayer's status is thus restored to 1200 points and level 2.- So, to sum-up, we were able to store a snapshot of
CurrentPlayerStatusand then restore it later. This is how the Memento Design Pattern works.
Gang of Four (GOF) Design Patterns on JavaBrahman
Creational Patterns: Factory method PatternFactory Method Design Pattern in Java Builder PatternBuilder Design Pattern in Java Prototype PatternPrototype Design Pattern in Java
Behavioral Patterns: Chain of Responsibility PatternChain of Responsibility Design Pattern in Java Observer PatternObserver Design Pattern in Java Iterator PatternIterator Design Pattern in Java State PatternState Design Pattern in Java Memento PatternMemento Design Pattern in Java Visitor PatternVisitor Design Pattern in Java Strategy PatternStrategy Design Pattern in Java Template Method PatternTemplate Method Design Pattern in Java
Structural Patterns: Adapter PatternAdapter design pattern in Java Composite PatternComposite Design Pattern in Java Facade PatternFacade Design Pattern in Java Proxy Pattern Java Proxy Design Pattern in Java
Analysis of Patterns: Strategy vs State PatternStrategy Design Pattern versus State Design Pattern
Creational Patterns: Factory method PatternFactory Method Design Pattern in Java Builder PatternBuilder Design Pattern in Java Prototype PatternPrototype Design Pattern in Java
Behavioral Patterns: Chain of Responsibility PatternChain of Responsibility Design Pattern in Java Observer PatternObserver Design Pattern in Java Iterator PatternIterator Design Pattern in Java State PatternState Design Pattern in Java Memento PatternMemento Design Pattern in Java Visitor PatternVisitor Design Pattern in Java Strategy PatternStrategy Design Pattern in Java Template Method PatternTemplate Method Design Pattern in Java
Structural Patterns: Adapter PatternAdapter design pattern in Java Composite PatternComposite Design Pattern in Java Facade PatternFacade Design Pattern in Java Proxy Pattern Java Proxy Design Pattern in Java
Analysis of Patterns: Strategy vs State PatternStrategy Design Pattern versus State Design Pattern