Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Memento pattern
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
== C# example == The memento pattern allows one to capture the internal state of an object without violating encapsulation such that later one can undo/revert the changes if required. Here one can see that the ''memento object'' is actually used to ''revert'' the changes made in the object. <syntaxhighlight lang="csharp"> class Memento { private readonly string savedState; private Memento(string stateToSave) { savedState = stateToSave; } public class Originator { private string state; // The class could also contain additional data that is not part of the // state saved in the memento. public void Set(string state) { Console.WriteLine("Originator: Setting state to " + state); this.state = state; } public Memento SaveToMemento() { Console.WriteLine("Originator: Saving to Memento."); return new Memento(state); } public void RestoreFromMemento(Memento memento) { state = memento.savedState; Console.WriteLine("Originator: State after restoring from Memento: " + state); } } } class Caretaker { static void Main(string[] args) { var savedStates = new List<Memento>(); var originator = new Memento.Originator(); originator.Set("State1"); originator.Set("State2"); savedStates.Add(originator.SaveToMemento()); originator.Set("State3"); // We can request multiple mementos, and choose which one to roll back to. savedStates.Add(originator.SaveToMemento()); originator.Set("State4"); originator.RestoreFromMemento(savedStates[1]); } } </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)