Memento Design Pattern falls under Behavioral Pattern of Gang of Four (GOF) Design Patterns in .Net. The command pattern is commonly used in the menu systems of many applications such as Editor, IDE, etc. In this article, I would like to share what is memento pattern and how is it work?
Memento design pattern used to capture the current state of an object and store it in such a manner that it can be restored at a later time without breaking the rules of encapsulation.
This pattern is commonly used in the menu systems of many applications such as Editor, IDE, etc.
The UML class diagram for the implementation of the Memento Design Pattern is given below:
The classes, interfaces, and objects in the above UML class diagram are as follows:
This is a class that creates a memento object containing a snapshot of the Originator's current state. It also restores the Originator to a previously stored state by using SetMemento operation.
This is a class that holds the information about the Originator’s saved state.
This is a class that is used to hold a Memento object for later use. This acts as a store only; it never examines or modifies the contents of the Memento object.
public class Originator { private string state; public Memento CreateMemento() { return new Memento(state); } public void SetMemento(Memento memento) { this.state = memento.GetState(); } } public class Memento { private string state; public Memento(string state) { this.state = state; } public string GetState() { return state; } } public class Caretaker { public Memento Memento { get; set; } }
The state of an object needs to be saved and restored at a later time.
The state of an object cannot be exposed directly by using an interface without exposing implementation.