The Memento Pattern itself seems pretty straight forward. I'm considering implementing the same as the wikipedia example, but before I do are there any language features of C# that make it easier to implement or use?
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.
Memento is a behavioral design pattern that allows making snapshots of an object's state and restoring it in future. The Memento doesn't compromise the internal structure of the object it works with, as well as data kept inside the snapshots.
Benefits of using memento design patternIt stores the objects state without compromising encapsulation. You can produce snapshots of the object's state without violating its encapsulation. You can simplify the originator's code by letting the caretaker maintain the history of the originator's state.
One obvious feature would be generics, implementing an generic memento will allow you to use it for any object you want.
Many examples that you will see will use a string (including all those currently among the replies to this question) as state which is a problem since it's one of the few types in .NET which are immutable.
When dealing with mutable objects (like any reference type with a setter-property) you have to remember though that when you save the memento you need to create a deepcopy of the object. Otherwise whenever you change your original object you will change your memento.
You could do this by using a serializer like protobuf-net or json.net since they don't require you to mark your objects with serializable attribute like the normal .net serialization mechanism does.
Codeproject have few articles about generic memento implementations, but they tend to skip the deepcopy part:
Generic Memento Pattern for Undo-Redo in C#
Memento Design Pattern
I'm not aware of any already built-in way to support Memento
pattern.
I see a couple of implementations by using .NET Mock frameworks, where in practise a clone of the object is created and can be field with a data, but I consider it kind of overhead.
The use Memento
patter on Undo/Redo usually, probably you too. In this case, it's better to have as less data on Undo/Redo stack as possible, so the custom undoable object
is something that I would go for.
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With