What is the Memento pattern?
The state of an object can be saved in the memento pattern so that it can be restored to this state later. The special thing about this is that the encapsulation of the object not is violated. This behavioral design pattern is also available as Snapshot or Token known.
When can you use the Memento pattern?
Probably the most obvious use case for the pattern is the well-known Undo/Redo-feature in various applications. Another example of practical application is the (transaction) logging of objects or entire application states in any form.
There are two players in the memento pattern: originator and caretaker.
The Caretaker is responsible for storing and managing the memento - but does not change it. It can request a memento from the originator in order to save the internal state of the originator (1). However, the caretaker has no access to the internal state of the memento. And it can pass a memento back to the originator to restore the internal state (2).
The originator in turn generates the memento from its current, internal state (1) on request. When a memento is received, the originator restores the "old" state (2). It therefore provides the interface for the memento.

Source: https://en.wikipedia.org/wiki/Memento_pattern
What does the Memento pattern look like in JavaScript?
The implementation using the example of a "Notes" app looks like this in JavaScript:
// Originator
var Notes = function(){
this.value= "" ;
this.saveState = function(){
return new NotesState(this)
}
this.restoreState = function(_obj){
this.value= _obj.value;
}
}
// Memento
var NotesState = function(_obj){
this.value = _obj.value ;
}
// CareTaker
var CareTaker = function(){
var conState = null;
this.SetNotesState = function(_conState){
conState = _conState;
}
this.GetNotesState = function(){
return conState;
}
}
// Usage
var notes = new Notes();
notes.value = 'Test 1';
console.log('Notizen:', notes);
var careTaker = new CareTaker();
console.log('Snaphot...');
careTaker.SetNotesState(notes.saveState());
console.log('Notizen ändern...');
notes.value = 'Test 2';
console.log('Notizen:', notes);
console.log('Rückgängig machen...');
notes.restoreState(careTaker.GetNotesState());
console.log('Notizen:', notes);
Tip: the code can be pasted 1:1 into the browser console for testing.
But be careful: The Memento pattern not only has advantages, but can also cause enormous performance losses if used incorrectly (too frequently).
Learn more about Java programming



