This content originally appeared on DEV Community and was authored by Juarez Júnior
The Memento pattern is used to capture and store the internal state of an object so that it can be restored later without violating encapsulation. It’s useful in situations where you want to implement "undo" or "restore" functionality in a system, such as in text editors that allow users to undo changes.
C# Code Example:
// Memento class that stores the state
public class Memento
{
public string State { get; private set; }
public Memento(string state)
{
State = state;
}
}
// Originator class that uses the Memento to save and restore its state
public class Originator
{
public string State { get; set; }
public Memento SaveState()
{
return new Memento(State);
}
public void RestoreState(Memento memento)
{
State = memento.State;
}
}
// Caretaker class that manages the history of states
public class Caretaker
{
private Stack<Memento> _history = new Stack<Memento>();
public void Save(Originator originator)
{
_history.Push(originator.SaveState());
}
public void Undo(Originator originator)
{
if (_history.Count > 0)
{
originator.RestoreState(_history.Pop());
}
}
}
class Program
{
static void Main(string[] args)
{
Originator originator = new Originator();
Caretaker caretaker = new Caretaker();
// Set state and save it
originator.State = "State 1";
caretaker.Save(originator);
// Change state and save it
originator.State = "State 2";
caretaker.Save(originator);
// Change state again
originator.State = "State 3";
Console.WriteLine($"Current state: {originator.State}");
// Undo to the previous state
caretaker.Undo(originator);
Console.WriteLine($"After undo: {originator.State}");
// Undo again
caretaker.Undo(originator);
Console.WriteLine($"After undo again: {originator.State}");
}
}
Code Explanation:
In this example, the Originator class has a state that can be saved and restored. The Memento class stores the state of the Originator, while the Caretaker class keeps a history of saved states and allows undoing changes. In the main program, the Originator's state is changed multiple times, and the undo operations restore previous states.
Conclusion:
The Memento pattern is ideal for systems that need to save and restore previous states of objects, such as in text editors or versioning systems. It enables undo functionality without violating object encapsulation.
Source code: GitHub
This content originally appeared on DEV Community and was authored by Juarez Júnior
Juarez Júnior | Sciencx (2024-10-11T12:00:00+00:00) C# Design Pattern: Memento. Retrieved from https://www.scien.cx/2024/10/11/c-design-pattern-memento/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.