備忘錄模式
Memento Pattern
是在不破壞封裝性的前提下,将對象目前的内部狀态儲存在對象之外,以便以後當需要時能将該對象恢複到原先儲存的狀态。備忘錄模式又叫快照模式,是一種對象行為型模式。
描述
備忘錄模式是關于捕獲和存儲對象的目前狀态的方式,以便以後可以平滑地恢複它。
優點
- 提供了一種可以恢複狀态的機制,當使用者需要時能夠比較友善地将資料恢複到某個曆史的狀态。
- 實作了内部狀态的封裝,除了建立它的發起類之外,其他對象都不能夠通路這些狀态資訊。
- 簡化了發起類,發起類不需要管理和儲存其内部狀态的各個備份,所有狀态資訊都儲存在備忘錄中,并由管理者進行管理,這符合單一職責原則。
缺點
- 資源消耗大,如果要儲存的内部狀态資訊過多或者特别頻繁,将會占用比較大的記憶體資源。
适用環境
- 需要儲存/恢複資料的相關狀态場景。
- 提供一個可復原的操作。
實作
// 以文本編輯器為例,該編輯器會不時地儲存狀态,并且可以根據需要進行恢複。
class EditorMemento { // memento對象将能夠保持編輯器狀态
constructor(content) {
this._content = content;
}
getContent() {
return this._content;
}
}
class Editor {
constructor(){
this._content = "";
}
type(words) {
this._content = `${this._content} ${words}`;
}
getContent() {
return this._content;
}
save() {
return new EditorMemento(this._content);
}
restore(memento) {
this._content = memento.getContent();
}
}
(function(){
const editor = new Editor()
editor.type("This is the first sentence.");
editor.type("This is second.");
const saved = editor.save();
editor.type("And this is third.")
console.log(editor.getContent()); // This is the first sentence. This is second. And this is third.
editor.restore(saved);
console.log(editor.getContent()); // This is the first sentence. This is second.
})();
每日一題
https://github.com/WindrunnerMax/EveryDay
參考
https://github.com/Byronlee/Design-patterns
https://www.runoob.com/design-pattern/memento-pattern.html
https://github.com/sohamkamani/javascript-design-patterns-for-humans#-memento