Memento

WHAT?

HOW?

WHY?

Code

class EditorMemento {
    constructor(content) {
        this._content = content
    }
    
    getContent() {
        return this._content
    }
}

class Editor {
    constructor(){
        this._content = ''
    }
    
    type(words) {
        this._content = this._content + ' ' + words
    }
    
    getContent() {
        return this._content
    }
    
    save() {
        return new EditorMemento(this._content)
    }
    
    restore(memento) {
        this._content = memento.getContent()
    }
}

const editor = new Editor()

// Type some stuff
editor.type('This is the first sentence.')


editor.type('This is second.')

// Save the state to restore to : This is the first sentence. This is second.

const saved = editor.save()


// Type some more
editor.type('And this is third.')




// Output: Content before Saving
console.log(editor.getContent())
// This is the first sentence. This is second. And this is third.

// Restoring to last saved state

editor.restore(saved);

console.log(editor);

console.log(editor.getContent())

// This is the first sentence. This is second.
var Person = function(name, street, city, state) {
    this.name = name;
    this.street = street;
    this.city = city;
    this.state = state;
}
 
Person.prototype = {
 
    hydrate: function() {
        var memento = JSON.stringify(this);
        return memento;
    },
 
    dehydrate: function(memento) {
        var m = JSON.parse(memento);
        this.name = m.name;
        this.street = m.street;
        this.city = m.city;
        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];
    }
}
 
// log helper
var log = (function () {
    var log = "";
 
    return {
        add: function (msg) { log += msg + "\n"; },
        show: function () { alert(log); log = ""; }
    }
})();
 
 
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
 
    mike.name = "King Kong";
    john.name = "Superman";
 
    // restore original state
 
    mike.dehydrate(caretaker.get(1));
    john.dehydrate(caretaker.get(2));
 
    log.add(mike.name);
    log.add(john.name);
 
    log.show();

THX

Memento

By just Just

Memento

  • 33