Zachary W. Huang

Home Projects Blog Guides Resume

Memento

Idea: Capture an object’s internal state in another object so it can be stored/restored at a later time. Note that a memento also makes it so that we can interact with an object’s state without violating encapsulation (as long as the client doesn’t ever “peek into” a memento).

class Memento {
  state: any;

  constructor(state: any) {
    this.state = state;
  }

  getState() {
    return this.state;
  }

  setState(state: any) {
    this.state = state;
  }
}

class Originator {
  state: any;

  constructor(state: any) {
    this.state = state;
  }

  createMemento(): Memento {
    return new Memento(this.state);
  }

  setMemento(memento: Memento) {
    this.state = memento.getState();
  }

  doThing() {
    console.log(this.state);
  }
}

function main() {
  const originator = new Originator("World!");
  const memento = originator.createMemento()
  originator.state = "Hello"
  originator.doThing(); // "Hello"
  originator.setMemento(memento);
  originator.doThing(); // "World!"
}
RSS icon github logo linkedin logo

Zachary W. Huang © 2021-2024