Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the Memento Pattern implemented in C#4?

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?

like image 311
Dave Hillier Avatar asked Jan 24 '12 21:01

Dave Hillier


People also ask

What function does the Memento pattern perform?

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.

What is Memento pattern in C#?

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.

What is Memento pattern explain its usage along with pros and cons?

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.


2 Answers

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

like image 114
Simon Stender Boisen Avatar answered Sep 25 '22 13:09

Simon Stender Boisen


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.

like image 42
Tigran Avatar answered Sep 23 '22 13:09

Tigran