Design patterns are proven solutions to software design problems. They help improve code quality, promote reusability, and increase maintainability. We use them to save time and produce quality, extensible and flexible code. In this article, we are going to introduce the Memento design pattern.
The Memento design pattern is a behavioral pattern that allows an object to save its previous state so that it can easily return to that state later. This pattern is useful when you want to restore an object to a previous state or when you need to undo a series of actions.
The Memento template consists of three main components:
Here is a simple example of how to implement the Memento template in C#:
class Originator
{
private string _state;
public void SetState(string state)
{
_state = state;
}
public Memento CreateMemento()
{
return new Memento(_state);
}
public void RestoreMemento(Memento memento)
{
_state = memento.GetState();
}
public void ShowState()
{
Console.WriteLine($"Current state: {_state}");
}
}
class Memento
{
private readonly string _state;
public Memento(string state)
{
_state = state;
}
public string GetState()
{
return _state;
}
}
class Caretaker
{
private Memento _memento;
public void SaveState(Originator originator)
{
_memento = originator.CreateMemento();
}
public void RestoreState(Originator originator)
{
originator.RestoreMemento(_memento);
}
}
// Usage example
var originator = new Originator();
var caretaker = new Caretaker();
originator.SetState("State 1");
originator.ShowState(); // Current state: State 1
caretaker.SaveState(originator);
originator.SetState("State 2");
originator.ShowState(); // Current state: State 2
caretaker.RestoreState(originator);
originator.ShowState(); // Current state: State 1
In this example, first, an Originator object is created, which is the object whose state we need to store. Then we create an instance of Caretaker to manage the state of this object. During the program, we can assign different states to the originator object as many times as we want. If we want to save its current state, we do this by using the created caretaker object and calling the SaveState method. In the future, if we want to return to the previous state, we must do this by using the caretaker object and calling the RestoreState method.
The Memento design pattern is a useful behavior pattern that allows an object to save and retrieve its state. Using this pattern, we can maintain object state history and enable undo/redo in an application.
To read about other design patterns, you can use the list below. There is also a code repository on GitHub that includes all the design patterns.
I am Reza Babakhani, a software developer. Here I write my experiences, opinions and suggestions about technology. I hope that what I write is useful for you.
leave a comment