class Person { constructor(name, age) { this.name = name; this.age = age; } }
class Memento { constructor(state) { this.state = state; } getState() { return this.state; } setState(state) { this.state = state; } }
class Caretaker { constructor() { this.memento = null; } getMemento() { return this.memento; } setMemento(memento) { this.memento = memento; } }
const person = new Person('John', 25); console.log(person); // Output: Person { name: 'John', age: 25 }
const caretaker = new Caretaker(); caretaker.setMemento(new Memento(person));
person.name = 'Tom'; person.age = 30; console.log(person); // Output: Person { name: 'Tom', age: 30 } // 恢复到之前的状态 person = caretaker.getMemento().getState(); console.log(person); // Output: Person { name: 'John', age: 25 }
本文为翻滚的胖子原创文章,转载无需和我联系,但请注明来自猿教程iskeys.com