Contact Me

Memento

 The Memento pattern allows an object to return to a previous state by saving and restoring an object's state at a given point in time. This is useful in situations where you need to undo operations or restore an object's state to a previous state.


Here is an example of how the Memento pattern can be implemented:


class Memento {

constructor(state) {

  this.state = state;

}

getState() {

  return this.state;

}

}


// Originator class

class Originator {

constructor() {

  this.state = '';

}

setState(state) {

  this.state = state;

}

getState() {

  return this.state;

}

saveStateToMemento() {

  return new Memento(this.state);

}

getStateFromMemento(memento) {

  this.state = memento.getState();

}

}


// Caretaker class

class Caretaker {

constructor() {

  this.mementoList = [];

}

add(memento) {

  this.mementoList.push(memento);

}

get(index) {

  return this.mementoList[index];

}

}



const originator = new Originator();

const caretaker = new Caretaker();

originator.setState('State 1');

originator.setState('State 2');

caretaker.add(originator.saveStateToMemento());

originator.setState('State 3');

caretaker.add(originator.saveStateToMemento());

originator.setState('State 4');

console.log(originator.getState());

// Output: State 4

originator.getStateFromMemento(caretaker.get(1));

console.log(originator.getState());

// Output: State 3

originator.getStateFromMemento(caretaker.get(0));

console.log(originator.getState());

// Output: State 2


In this example, we have three classes: Memento, Originator and Caretaker. The Memento class represents the object that stores the state of an object at a given time. The Originator class is the object whose state needs to be saved and restored. Finally, the Caretaker class is responsible for storing the Memento objects and providing access to them.

In the example usage section above, we created an instance of the Originator class and the Caretaker class. Then we change the state of the instance of the Originator class twice and save the intermediate states

the instance of the Originator class changes state one more time and adds the last state to the object of the Caretaker class. It then changes the state again and displays the current state. After that, we use the getStateFromMemento() method of the Originator class instance to restore the previous state from an object of the Memento class stored in the Caretaker class. This allows us to undo the last operation and display the previous state.

Finally, we restore the even older state of the Memento class stored in the Caretaker class and display the state again.