The Memo Pattern, also known as the Memento Pattern, is a type of object behavioral pattern that involves capturing and storing an object's current state so that it can be smoothly restored later without compromising encapsulation.
Provides a mechanism for restoring state, making it convenient for users to restore data to a specific historical state when needed.
Encapsulates internal state, preventing other objects from accessing this state information except for the originating class.
Simplifies the originating class, which no longer needs to manage and store various backups of its internal state; all state information is saved in a memento and managed by a caretaker, thus adhering to the single responsibility principle.
Consumes a large amount of resources; if a large amount of internal state information needs to be saved or if saving occurs frequently, it can consume significant memory resources.
// Taking a text editor as an example, the editor periodically saves its state and can restore it as needed.classEditorMemento{// The memento object can preserve the editor's stateconstructor(content){this._content = content;}getContent(){returnthis._content;}}classEditor{constructor(){this._content ="";}type(words){this._content =`${this._content}${words}`;}getContent(){returnthis._content;}save(){returnnewEditorMemento(this._content);}restore(memento){this._content = memento.getContent();}}(function(){const editor =newEditor() editor.type("This is the first sentence."); editor.type("This is the second sentence.");const saved = editor.save(); editor.type("And this is the third sentence.") console.log(editor.getContent());// This is the first sentence. This is the second sentence. And this is the third sentence. editor.restore(saved); console.log(editor.getContent());// This is the first sentence. This is the second sentence.})();