Design Patterns


Capture and restore an object's internal state
  • The Memento pattern provides temporary storage as well as restoration of an object.
  • The mechanism in which you store the object’s state depends on the required duration of persistence, which may vary.
  • You could view a database as an implementation of the Memento design pattern in which objects are persisted and restored.
  • However, the most common reason for using this pattern is to capture a snapshot of an object’s state so that any subsequent changes can be undone easily if necessary.
  • In JavaScript Mementos are easily implemented by serializing and de-serializing objects with JSON.
var Person = function(name, street, city, state) { = name;
this.street = street; = city;
this.state = state;
Person.prototype = {
hydrate: function() {
var memento = JSON.stringify(this);
return memento;
dehydrate: function(memento) {
var m = JSON.parse(memento); =;
this.street = m.street; =;
this.state = m.state;
var CareTaker = function() {
this.mementos = {};
this.add = function(key, memento) {
this.mementos[key] = memento;
this.get = function(key) {
return this.mementos[key];
function run() {
var mike = new Person("Mike Foley", "1112 Main", "Dallas", "TX");
var john = new Person("John Wang", "48th Street", "San Jose", "CA");
var caretaker = new CareTaker();
// save state
caretaker.add(1, mike.hydrate());
caretaker.add(2, john.hydrate());
// mess up their names = "King Kong"; = "Superman";
// restore original state
Last modified 3yr ago