The Memento design pattern is a behavioral pattern that allows you to capture an object’s internal state and save it so that the object can be restored to that state later. It’s often used when you need to implement undo functionality or save and restore the state of an object. Here’s a C# example of the Memento pattern with a use case of a text editor that allows undoing changes.
Define the Memento
public class EditorMemento
{
public string Text { get; private set }
public EditorMemento(string text)
{
Text = text;
}
}
Create the Originator (TextEditor)
public class TextEditor
{
private string text;
public TextEditor()
{
text = string.Empty;
}
public void Write(string newText)
{
text += newText;
}
public void Print()
{
Console.WriteLine("Current Text: " + text);
}
public EditorMemento Save()
{
return new EditorMemento(text);
}
public void Restore(EditorMemento memento)
{
text = memento.Text;
}
}
Implement the Caretaker (EditorHistory) to manage mementos
public class EditorHistory
{
private Stack<EditorMemento> mementos = new Stack<EditorMemento>();
public void Push(EditorMemento memento)
{
mementos.Push(memento);
}
public EditorMemento Pop()
{
return mementos.Pop();
}
}
Use Case – Text Editor with Undo Functionality
class Program
{
static void Main(string[] args)
{
var editor = new TextEditor();
var history = new EditorHistory();
editor.Write("Hello, ");
history.Push(editor.Save());
editor.Write("world!");
editor.Print(); // Current Text: Hello, world!
editor.Write(" This is the Memento pattern.");
history.Push(editor.Save());
editor.Print(); // Current Text: Hello, world! This is the Memento pattern.
// Perform undo to revert to the previous state
editor.Restore(history.Pop());
editor.Print(); // Current Text: Hello, world!
}
}
In this example, we have a TextEditor
that allows you to write and print text. The EditorHistory
acts as a caretaker, managing the history of mementos (states) that are saved when you perform an action. When you need to undo an action, you can restore the editor’s state using the memento from the history.
The Memento pattern allows you to capture and restore the internal state of an object without violating encapsulation. It’s especially useful in scenarios where you need to implement undo/redo functionality or save and restore states in an application.