Zachary W. Huang
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!"
}