可以使用此模式的一个例子是将物件回复到其先前的状态
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
hydrate() {
return { ...this };
}
deydreate({ name, age }) {
this.name = name;
this.age = age;
}
}
class Store {
constructor() {
this.store = {};
}
add(key, value) {
this.store[key] = value;
}
get(key) {
return this.store[key];
}
}const dao = new Person("dao", 12);
const lang = new Person("lang", 30);
const store = new Store();
store.add(1, dao.hydrate());
store.add(2, lang.hydrate());
dao.name = "newdao";
lang.name = "newlang";
console.log(dao);
console.log(lang);
dao.deydreate(store.get(1));
lang.deydreate(store.get(2));
console.log(dao);
console.log(lang);