2. Memento Design Pattern
• Memento pattern is used to restore the state of an
object to a previous state.
• Memento pattern falls under the behavioral pattern
category.
3. Implementation
• Memento pattern uses three actor classes.
– Memento contains state of an object to be
restored.
– Originator creates and stores states in Memento
objects and
– Caretaker object is responsible to restore object
state from Memento.
4. Intent
• Capture and externalize an object’s state without violating
encapsulation.
• Restore the object’s state at some later time.
– Useful when implementing checkpoints and undo
mechanisms that let users back out of tentative operations
or recover from errors.
– Entrusts other objects with the information it needs to
revert to a previous state without exposing its internal
structure and representations.
5. Forces
• Application needs to capture states at certain times
or at user discretion. May be used for:
– Undo / redo
– Log errors or events
– Backtracking
• Need to preserve encapsulation
– Don’t share knowledge of state with other objects
• Object owning state may not know when to take
state snapshot.
6. Memento Pattern – Motivation
• Sometimes it's necessary to record the internal state of an object.
– This is required when implementing checkpoints and undo mechanisms
– Exposing this state would violate encapsulation
• A memento is an object that stores a snapshot of the internal state of
another object—the memento's originator.
• The undo mechanism will request a memento from the originator
when it needs to checkpoint the originator's state.
• The originator initializes the memento with information that
characterizes its current state.
• Only the originator can store and retrieve information from the
memento—the memento is "opaque" to other objects.
7. Motivation
• Memento stores a snapshot of another object’s internal state,
exposure of which would violate encapsulation and compromise
the application’s reliability and extensibility.
• A graphical editor may encapsulate the connectivity
relationships between objects in a class, whose public interface
might be insufficient to allow precise reversal of a move
operation.
Move
Undo
8. Motivation
Memento pattern solves this problem as follows:
• The editor requests a memento from the object before
executing move operation.
• Originator creates and returns a memento.
• During undo operation, the editor gives the memento
back to the originator.
• Based on the information in the memento, the originator
restores itself to its previous state.
9. Applicability
• Use the Memento pattern when:
– A snapshot of an object’s state must be saved so
that it can be restored later, and
– direct access to the state would expose
implementation details and break encapsulation.
10. Participants
• Memento
– Stores internal state of the Originator object.
Originator decides how much.
– Protects against access by objects other than the
originator.
– Mementos have two interfaces:
• Caretaker sees a narrow interface.
• Originator sees a wide interface.
11. Participants (continued)
• Originator
– Creates a memento containing a snapshot of its
current internal state.
– Uses the memento to restore its internal state.
12. Caretaker
• Is responsible for the memento’s safekeeping.
• Never operates on or examines the contents of a
memento.
13. Collaborations
• A caretaker requests a memento from an originator,
holds it for a time, and passes it back to the
originator.
• Mementos are passive. Only the originator that
created a memento will assign or retrieve its state.
14. Consequences
• Memento has several consequences:
– Memento avoids exposing information that only
an originator should manage, but for simplicity
should be stored outside the originator.
– Having clients manage the state they ask for
simplifies the originator.
15. Consequences (continued)
• Using mementos may be expensive, due to copying
of large amounts of state or frequent creation of
mementos.
• A caretaker is responsible for deleting the mementos
it cares for.
• A caretaker may incur large storage costs when it
stores mementos.
16. Implementation
• When mementos get created and passed back to
their originator in a predictable sequence, then
Memento can save just incremental changes to
originator’s state.
17. Memento Pattern - Structure
• Intent
• Without violating encapsulation, capture and externalize an object's internal
state so that the object can be returned to this state later.
• Structure
18. 18
I/O streams, briefly
• stream: an abstraction of a source or target of data
• bytes "flow" to (output) and from (input) streams
• can represent many data sources:
– files on hard disk
– another computer on network
– web page
– input device
(keyboard, mouse, etc.)
20. 20
Serialization
• serialization: reading / writing
objects and their exact state
using I/O streams
– allows objects themselves to
be written to files, across
network, to internet, etc.
– lets you save your objects to
disk and restore later
– avoids converting object's
state into arbitrary text format
21. 21
Classes used for serialization
in java.io package:
• ObjectOutputStream class represents a connection to which an object can
be written / sent (saved)
public class ObjectOutputStream
public ObjectOutputStream(OutputStream out)
public void writeObject(Object o)
throws IOException
• ObjectInputStream class represents a connection from which an object
can be read / received (loaded)
public class ObjectInputStream
public ObjectInputStream(InputStream in)
public Object readObject() throws Exception
• FileInputStream, FileOutputStream can be constructed from a file name
String
22. 22
Serialization example
• recommendation: use a Memento class that has save/load code
// write the object named someObject to file "file.dat"
try {
OutputStream os = new FileOutputStream("file.dat");
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(someObject);
os.close();
} catch (IOException e) { ... }
// load the object named someObject from file "file.dat"
try {
InputStream is = new FileInputStream("file.dat");
ObjectInputStream ois = new ObjectInputStream(is);
ArrayList someList = (ArrayList)ois.readObject();
is.close();
} catch (Exception e) { ... }
23. 23
• must implement the (methodless) java.io.Serializable
interface for your class to be compatible with object
input/output streams
public class BankAccount implements Serializable
{
...
• ensure that all instance variables inside your class are either
serializable or declared transient
– transient fields won't be saved when object is serialized
Making your classes serializable
24. Memento Pattern – Example
private class Memento implements java.io.Serializable{
private int number;
private File file = null;
public Memento( Originator o){ number = o.number; file = o.file;}
}
public class Originator {
private int number; private File file = null;
public Originator(){}
public Memento getMemento() { return new Memento(this);}
public void setMemento(Memento m){number = m.number; file = m.file;}
}
25. Memento Pattern – Example
https//sourcemaking.com/design_patterns/memento/java/1
https://www.tutorialspoint.com/design_pattern/memento_pattern.htm
26. Credits
• TCSS 360, Spring 2005
Lecture Notes
• Jim Fawcett
CSE776 – Design Patterns
Summer 2005
• Chap 6 - Design Patterns