Created
July 12, 2022 13:55
-
-
Save wolivera/3ac0c324f53c13590e9667c953fd0ec6 to your computer and use it in GitHub Desktop.
GoF Memento
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Person { | |
constructor (name, street, city, state) { | |
this.name = name; | |
this.street = street; | |
this.city = city; | |
this.state = state; | |
} | |
hydrate () { | |
const memento = JSON.stringify(this); | |
return memento; | |
} | |
dehydrate (memento) { | |
const m = JSON.parse(memento); | |
this.name = m.name; | |
this.street = m.street; | |
this.city = m.city; | |
this.state = m.state; | |
} | |
} | |
class Contacts { | |
constructor () { | |
this.mementos = {}; | |
} | |
add (key, memento) { | |
this.mementos[key] = memento; | |
} | |
get (key) { | |
return this.mementos[key]; | |
} | |
} | |
const anne = new Person("Anne Foley", "1112 Main", "Dallas", "TX"); | |
const john = new Person("John Wang", "48th Street", "San Jose", "CA"); | |
const contacts = new Contacts(); | |
// save state | |
contacts.add(1, anne.hydrate()); | |
contacts.add(2, john.hydrate()); | |
// mess up their names | |
anne.name = "King Kong"; | |
john.name = "Superman"; | |
// restore original state | |
anne.dehydrate(contacts.get(1)); | |
john.dehydrate(contacts.get(2)); | |
console.log(anne.name); | |
console.log(john.name); | |
// Anne Foley | |
// John Wang |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment