Memento Pattern

Definition

Without violating encapsulation, capture and externalize an object’s internal state so that the object can be restored to this state later.

Explanation

The memento pattern is implemented with three objects: the originator, a caretaker and a memento. The originator is some object that has an internal state. The caretaker is going to do something to the originator, but wants to be able to undo the change. The caretaker first asks the originator for a memento object. Then it does whatever operation (or sequence of operations) it was going to do. To roll back to the state before the operations, it returns the memento object to the originator. The memento object itself is an opaque object (one which the caretaker cannot, or should not, change). When using this pattern, care should be taken if the originator may change other objects or resources – the memento pattern operates on a single object.

Screencast

TypeScript Code

module Memento {
    class PersonMemento {
        constructor(public firstName: string, public lastName: string, public age: number) {
        }
    }

    export class Person {
        constructor(public firstName: string, public lastName: string, public age: number) {
        }

        public GetMemento(): any {
            return new PersonMemento(this.firstName, this.lastName, this.age);
        }

        public RestoreMemento(state: any) {
            var personState = <PersonMemento>state;
            this.firstName = personState.firstName;
            this.lastName = personState.lastName;
            this.age = personState.age;
        }

        public display() {
            Output.WriteLine(this.firstName + " | " + this.lastName + " | " + this.age);
        }
    }
}

window.addEventListener("load", function () {
    var mementos = new Array();

    var person = new Memento.Person("Wesley", "Bakker", 36);
    person.display();

    mementos.push(person.GetMemento());

    person.firstName = "Sam";
    person.age = 3;
    person.display();

    mementos.push(person.GetMemento());

    person.firstName = "Imen";
    person.lastName = "ben Jeddou"
    person.age = 36;
    person.display();

    mementos.push(person.GetMemento());

    person.RestoreMemento(mementos[0]);
    person.display();

    person.RestoreMemento(mementos[1]);
    person.display();

    person.RestoreMemento(mementos[2]);
    person.display();
});

Output