Saturday, June 26, 2010

Memento Design Pattern

Design patterns, when dealing with software architecture, utilize the different principles of object oriented programming such as abstraction, encapsulation and inheritance to solve design and structural problems and create more efficient code. One such pattern is Memento, and it can be a very useful one when applied to game design.


The memento pattern allows us to take a snapshot of an object and pass it off to another object for later reference. This is usually accomplished with three objects, the originator, the caregiver and the memento. The originator is the object which has the data we would like to save. The caregiver is the object acting on the originator and receives the snapshot of the originator. The memento is the black box between them which actually is the copy of the data.



To visualize this pattern better let’s compare it to backing up work which you are currently working on. In this example, the originator is the current file which has the data which needs to be backed up before it can be changed. The caregiver is you, the user, the one who will receive the duplicate and then continue to work and make changes to the original. The memento is the backup itself, a snapshot of the file, unaltered, ready to be reopened when need be.

The memento pattern utilizes encapsulation but can break it by accessing class variables directly with a memento class that is a friend of the caretaker or originator. It also utilizes abstraction and reusability by giving us a snapshot of an object at runtime. We can respond to a variety of situations depending on this data. This method is good for utilizing features similar to undo and redo, where reverting to a previous instance is desirable. It can also be used for simulations that require less randomness and more response to hard data.

In games this pattern can be used to implement saving the game by obtaining a memento containing the necessary data to reload the game from a specific point. Another method it can also be used for, in conjunction with the command pattern, is to stack commands and perform sets of actions the same way more than once. It can be used for memory and puzzle games to remember guesses and positions as well as combo counting.

When it comes to games, design patterns can be used in a variety of different ways, sometimes not in the same exact way as they were originally intended for. However this is what makes them a great asset in that we can pick, choose, mix and match what is right for a specific situation and put our own spin on it. So experiment with design patterns like memento and don’t feel bad if the first few times you can’t find a good way to use it. Learn from implementations but more importantly learn from trying and making mistakes.

No comments:

Post a Comment