Memo Pattern

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.

Description

The Memo Pattern is a way of capturing and storing an object's current state so that it can be easily restored later.

Advantages

  • 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.

Disadvantages

  • 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.

Applicable Scenarios

  • Scenarios requiring the saving/restoring of related data states.
  • Providing a rollback operation.

Implementation

// Taking a text editor as an example, the editor periodically saves its state and can restore it as needed.

class EditorMemento { // The memento object can preserve the editor's state
    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 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.
})();

Daily Question

https://github.com/WindrunnerMax/EveryDay

References

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