Memento Pattern

Role

This pattern is used to capture an object's internal state and save it externally so that it can be restored later.

Illustration

Many computer games go on for a long time. Having a means to save a game's state so that it can be resumed at a later stage is very handy. It can also be useful to save what are known as "checkpoints" in a game so that it's possible to return to a previous checkpoint after a disastrous move. For example, here is a description of CilkChess, a chess program produced at MIT:

Cilk jobs may survive machine crashes or network outages despite the fact that Cilk programs have been coded with no special provision for handling machine or network failures. If a worker crashes, then other workers automatically redo any work that was lost in the crash. In the case of a more catastrophic failure, such as a power outage, a total network failure, or a crash of the file server, then all workers may crash. For this case, Cilk-NOW provides automatic checkpointing, so when service is restored, the Cilk job may be restarted with minimal lost work.

Some of the more humorous aspects of computer chess are summed up in the cartoon in Figure 10-7.[14]

Memento pattern illustration—computer chess

Figure 10-7. Memento pattern illustration—computer chess

Design

As indicated in the preceding quote, the saving of state can be made independent of the object itself, and this is a key point of the Memento pattern. ...

Get C# 3.0 Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.