Description
Memento pattern is used to restore state of an object to a previous state. Memento pattern falls under behavioral pattern category. The memento pattern uses three actors for the processes: the originator, a caretaker and a memento. The originator holds that has an internal state. The caretaker handles different states of the originator, but is able to undo the change.
This design pattern offers a way to store previous states of an object easily. The three actors involved are:
- Memento : the basic object that is stored in different states
- Originator : sets and get the values from the currently targeted moment; creates new mementos and assigns current values to them
- Caretaker : holds an ArrayList that contains all previous versions
of the memento. It can store and retrieve store mementos
Let’s define an originator that holds an article. It will have methods support for creating a memento and also to load a previous article from a save memento
Originator
public class Originator { public string Article { get; set; } public void Set(string newArticle) { Console.WriteLine("From originator : Current version of article"); Console.WriteLine("\'"+newArticle+ "\'"); this.Article = newArticle; } public Memento StoreInMemento() { Console.WriteLine("From originator saving to memento"); Console.WriteLine("\'"+Article+"\'"); return new Memento(Article); } public String RestoreFromMemento(Memento memento) { this.Article = memento.Article; Console.WriteLine("From originator. Restoring previously saved article"); Console.WriteLine("\'"+Article+ "\'"); return memento.Article; } }
Memento
public class Memento { public string Article { get; set; } public Memento(string article) { this.Article = article; } }
Caretaker
public class Caretaker { List saved = new List(); public void AddMemento(Memento m) { saved.Add(m); } public Memento GetMemento(int index) { return saved[index]; } }
class Program { static void Main(string[] args) { Caretaker caretaker = new Caretaker(); Originator originator = new Originator(); originator.Article = "My article 1"; //storing a state caretaker.AddMemento(originator.StoreInMemento()); originator.Article = "My article 2"; //storing a second state caretaker.AddMemento(originator.StoreInMemento()); //getting the first state Memento first = caretaker.GetMemento(0); //restoring the memento into the originator originator.RestoreFromMemento(first); Console.WriteLine(originator.Article); } }