Skip to content

Commit 97d0f40

Browse files
committed
Add "Memento" recipe to the "Design Patterns" chapter.
1 parent a2c0020 commit 97d0f40

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
---
2+
layout: recipe
3+
title: Memento Pattern
4+
chapter: Design Patterns
5+
---
6+
7+
h2. Problem
8+
9+
You want to anticipate the reversion of changes to an object.
10+
11+
h2. Solution
12+
13+
Use the "Memento pattern":http://en.wikipedia.org/wiki/Memento_pattern to track changes to an object. The class using the pattern will export a _memento_ object stored elsewhere.
14+
15+
If you have application where the user can edit a text file, for example, they may want to undo their last action. You can save the current state of the file before the user changes it and then roll back to that at a later point.
16+
17+
{% highlight coffeescript %}
18+
class PreserveableText
19+
class Memento
20+
constructor: (@text) ->
21+
22+
constructor: (@text) ->
23+
save: (newText) ->
24+
memento = new Memento @text
25+
@text = newText
26+
memento
27+
restore: (memento) ->
28+
@text = memento.text
29+
30+
pt = new PreserveableText "The original string"
31+
pt.text # => "The original string"
32+
33+
memento = pt.save "A new string"
34+
pt.text # => "A new string"
35+
36+
pt.save "Yet another string"
37+
pt.text # => "Yet another string"
38+
39+
pt.restore memento
40+
pt.text # => "The original string"
41+
{% endhighlight %}
42+
43+
h2. Discussion
44+
45+
The Memento object returned by _PreserveableText#save_ stores the important state information separately for safe-keeping. You could even serialize this Memento in order to maintain an "undo" buffer on the hard disk or remotely for such data-intensive objects as edited images.

wanted-recipes.textile

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,6 @@ h2. Design patterns
145145
** Interpreter
146146
** Iterator
147147
** Mediator
148-
** Memento
149148
** Observer
150149
** State
151150
** Template Method

0 commit comments

Comments
 (0)