Happy new Year everybody!
I’d like to begin 2010 with a design pattern argument.
First design pattern of this year is Memento pattern, that could be very useful if you are working on an AIR desktop application or in a Flex RIA and you want to make an history of user’s actions.
In fact this pattern is used to make undo and redo in an application.
Memento pattern is tightly coupled with originator object and it’s usually composed by 3 different parts:
Originator is object that pass data to caretaker and it saved them in a couple of arrays (undoArray and redoArray).
So caretaker is an object that stores a memento snapshot and, if originator needs, pass undo or redo data to this object.
I prepare a sample to understand better what could you use Memento pattern in your applications (“view source” option is activated).
I wrote a Memento class with a Singleton to centralize all users actions,then I create a MementoVO that is a dynamic class to help me store data from each object used by the user, you could use a simple Object instead of a dynamic class to save more memory if you prefer.
Sample is very easy but useful for Memento pattern purpose, in fact you can move windows trough the stage and our “history” class (Memento.as) saves their positions when saveAction method is called by the originator (an instance of CustomWin).
Memento class has 4 essentials methods that are:
I start from the end, saveRedoAction, last method, is used to save the position of a window before I restore its positions, usually Redo action is used only one time, but if you want you could create an Array and work with multiple Redo.
Another important method is saveAction that is called when mouse down event was triggered and it stores in memento class own old position and object itselfs.
First two methods need to undo and redo an user action, it’s easy isn’t it?!
I think that in this year I’ll share lots of those patterns with you to share our knowledge together so feel free to add comment at this post and we could make an interesting and useful conversation, I’m totally sure!