Memento
Context: Without violating encapsulation, capture and externalize an object’s internal state so that the object can be restored to this state later.
public class Memento{ public string State { get; } public Memento(string state) => State = state;}
public class Originator{ public string State { get; set; } public Memento Save() => new Memento(State); public void Restore(Memento m) => State = m.State;}
public class Caretaker{ public Memento Memento { get; set; }}Real-world usage example
Section titled “Real-world usage example”Undo mechanism: A text editor saves a memento before each change. The caretaker (history stack) stores mementos to restore previous states.
Example: In C#, serialization (binary, XML, JSON) can be used to save object state – a form of memento. Also, ITrackable in Entity Framework Core tracks original values for concurrency.