备忘录模式
特点
- 随时记录一个对象的状态变化
- 被记录实例中需要提供一个生成记录实例的方法,以及根据生成实例还原成被记录实例的方法
- 随时可以恢复之前的某个状态(如 撤销功能)
demo
更多详细代码
// 记录类(扩展理解:将被记录类压缩进行记录,并提供还原方法)
function Memento(content) {
this.content = content;
}
Memento.prototype.getContent = function () {
return this.content;
};
// 记录列表
function CareTaker() {
this.list = [];
}
CareTaker.prototype.add = function (memento) {
this.list.push(memento);
};
CareTaker.prototype.getMemento = function (index) {
return this.list[index];
};
// 被记录类
function Editor() {
this.content = null;
}
Editor.prototype.setContent = function (content) {
this.content = content;
};
// 将需要记录内容进行实例化
Editor.prototype.saveMemento = function () {
return new Memento(this.content);
};
Editor.prototype.getContentFromMemento = function (memento) {
this.content = memento.getContent();
};
Editor.prototype.getContent = function () {
console.log(this.content);
};
// 构造存储列表
const careTaker = new CareTaker();
// 构造被记录类
const editor = new Editor();
editor.setContent("111");
careTaker.add(editor.saveMemento());
editor.setContent("222");
editor.getContent();
editor.getContentFromMemento(careTaker.getMemento(0));
editor.getContent();