SlideShare a Scribd company logo
1 of 26
Memento Design Pattern
CECS277
Fall 2017
Mimi Opkins
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.
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.
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.
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.
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.
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
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.
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.
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.
Participants (continued)
• Originator
– Creates a memento containing a snapshot of its
current internal state.
– Uses the memento to restore its internal state.
Caretaker
• Is responsible for the memento’s safekeeping.
• Never operates on or examines the contents of a
memento.
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.
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.
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.
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.
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
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.)
19
Stream hierarchy
java.io.InputStream
AudioInputStream
FileInputStream
ObjectInputStream
java.io.OutputStream
ByteArrayOutputStream
FileOutputStream
ObjectOutputStream
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
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
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
• 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
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;}
}
Memento Pattern – Example
https//sourcemaking.com/design_patterns/memento/java/1
https://www.tutorialspoint.com/design_pattern/memento_pattern.htm
Credits
• TCSS 360, Spring 2005
Lecture Notes
• Jim Fawcett
CSE776 – Design Patterns
Summer 2005
• Chap 6 - Design Patterns

More Related Content

Similar to 13785038.ppt

Basics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdfBasics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdfKnoldus Inc.
 
Conceptual modeling of information systems
Conceptual modeling of information systemsConceptual modeling of information systems
Conceptual modeling of information systemsegeda9
 
Ejb3.1 for the starter
Ejb3.1 for the starterEjb3.1 for the starter
Ejb3.1 for the startershohancse
 
OOP02-27022023-090456am.pptx
OOP02-27022023-090456am.pptxOOP02-27022023-090456am.pptx
OOP02-27022023-090456am.pptxuzairrrfr
 
Software Engineering : OOAD using UML
Software Engineering : OOAD using UMLSoftware Engineering : OOAD using UML
Software Engineering : OOAD using UMLAjit Nayak
 
ORM Concepts and JPA 2.0 Specifications
ORM Concepts and JPA 2.0 SpecificationsORM Concepts and JPA 2.0 Specifications
ORM Concepts and JPA 2.0 SpecificationsAhmed Ramzy
 
Elements for an iOS Backend
Elements for an iOS BackendElements for an iOS Backend
Elements for an iOS BackendLaurent Cerveau
 
Ch. 3 classes and objects
Ch. 3 classes and objectsCh. 3 classes and objects
Ch. 3 classes and objectsdkohreidze
 
iOS Application Penetration Testing for Beginners
iOS Application Penetration Testing for BeginnersiOS Application Penetration Testing for Beginners
iOS Application Penetration Testing for BeginnersRyanISI
 
Adbms 1 object oriented modeling
Adbms 1 object oriented modelingAdbms 1 object oriented modeling
Adbms 1 object oriented modelingVaibhav Khanna
 
Flex modular applications using robotlegs
Flex modular applications using robotlegsFlex modular applications using robotlegs
Flex modular applications using robotlegsSaurabh Narula
 

Similar to 13785038.ppt (20)

iOS (7) Workshop
iOS (7) WorkshopiOS (7) Workshop
iOS (7) Workshop
 
Javasession10
Javasession10Javasession10
Javasession10
 
Basics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdfBasics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdf
 
Java applets
Java appletsJava applets
Java applets
 
Mobile Application Development class 006
Mobile Application Development class 006Mobile Application Development class 006
Mobile Application Development class 006
 
Conceptual modeling of information systems
Conceptual modeling of information systemsConceptual modeling of information systems
Conceptual modeling of information systems
 
Spring framework
Spring frameworkSpring framework
Spring framework
 
Ejb3.1 for the starter
Ejb3.1 for the starterEjb3.1 for the starter
Ejb3.1 for the starter
 
OOP02-27022023-090456am.pptx
OOP02-27022023-090456am.pptxOOP02-27022023-090456am.pptx
OOP02-27022023-090456am.pptx
 
React Native Firebase
React Native FirebaseReact Native Firebase
React Native Firebase
 
Scheduling Thread
Scheduling  ThreadScheduling  Thread
Scheduling Thread
 
Software Engineering : OOAD using UML
Software Engineering : OOAD using UMLSoftware Engineering : OOAD using UML
Software Engineering : OOAD using UML
 
ORM Concepts and JPA 2.0 Specifications
ORM Concepts and JPA 2.0 SpecificationsORM Concepts and JPA 2.0 Specifications
ORM Concepts and JPA 2.0 Specifications
 
Elements for an iOS Backend
Elements for an iOS BackendElements for an iOS Backend
Elements for an iOS Backend
 
Ch. 3 classes and objects
Ch. 3 classes and objectsCh. 3 classes and objects
Ch. 3 classes and objects
 
Life Cyrcle.pptx
Life Cyrcle.pptxLife Cyrcle.pptx
Life Cyrcle.pptx
 
iOS Application Penetration Testing for Beginners
iOS Application Penetration Testing for BeginnersiOS Application Penetration Testing for Beginners
iOS Application Penetration Testing for Beginners
 
CoreData
CoreDataCoreData
CoreData
 
Adbms 1 object oriented modeling
Adbms 1 object oriented modelingAdbms 1 object oriented modeling
Adbms 1 object oriented modeling
 
Flex modular applications using robotlegs
Flex modular applications using robotlegsFlex modular applications using robotlegs
Flex modular applications using robotlegs
 

Recently uploaded

NO1 Popular kala jadu karne wale ka contact number kala jadu karne wale baba ...
NO1 Popular kala jadu karne wale ka contact number kala jadu karne wale baba ...NO1 Popular kala jadu karne wale ka contact number kala jadu karne wale baba ...
NO1 Popular kala jadu karne wale ka contact number kala jadu karne wale baba ...Amil baba
 
Webhost NVME Cloud VPS Hosting1234455678
Webhost NVME Cloud VPS Hosting1234455678Webhost NVME Cloud VPS Hosting1234455678
Webhost NVME Cloud VPS Hosting1234455678Cloud99 Cloud
 
And that's about to change! (Service Design Drinks Berlin May 2024)
And that's about to change! (Service Design Drinks Berlin May 2024)And that's about to change! (Service Design Drinks Berlin May 2024)
And that's about to change! (Service Design Drinks Berlin May 2024)☕ 🥧 🚲 Martin Gude
 
BIT Khushi gandhi project.pdf graphic design
BIT Khushi gandhi project.pdf graphic designBIT Khushi gandhi project.pdf graphic design
BIT Khushi gandhi project.pdf graphic designKhushiGandhi15
 
Latest Trends in Home and Building Design
Latest Trends in Home and Building DesignLatest Trends in Home and Building Design
Latest Trends in Home and Building DesignResDraft
 
NO1 Best Best Amil In Rawalpindi Bangali Baba In Rawalpindi jadu tona karne w...
NO1 Best Best Amil In Rawalpindi Bangali Baba In Rawalpindi jadu tona karne w...NO1 Best Best Amil In Rawalpindi Bangali Baba In Rawalpindi jadu tona karne w...
NO1 Best Best Amil In Rawalpindi Bangali Baba In Rawalpindi jadu tona karne w...Amil baba
 
Digital Marketing Company in Bangalore.pdf
Digital Marketing Company in Bangalore.pdfDigital Marketing Company in Bangalore.pdf
Digital Marketing Company in Bangalore.pdfOnecity
 
NO1 Best Best Black Magic Specialist Near Me Spiritual Healer Powerful Love S...
NO1 Best Best Black Magic Specialist Near Me Spiritual Healer Powerful Love S...NO1 Best Best Black Magic Specialist Near Me Spiritual Healer Powerful Love S...
NO1 Best Best Black Magic Specialist Near Me Spiritual Healer Powerful Love S...Amil baba
 
Game Pitch- Heroes of Niflheim (a mobile game).pdf
Game Pitch- Heroes of Niflheim (a mobile game).pdfGame Pitch- Heroes of Niflheim (a mobile game).pdf
Game Pitch- Heroes of Niflheim (a mobile game).pdfphinehasosebi
 
Spring Summer 26 Colors Trend Book Peclers Paris
Spring Summer 26 Colors Trend Book Peclers ParisSpring Summer 26 Colors Trend Book Peclers Paris
Spring Summer 26 Colors Trend Book Peclers ParisPeclers Paris
 
Abortion Clinic in Springs +27791653574 Springs WhatsApp Abortion Clinic Serv...
Abortion Clinic in Springs +27791653574 Springs WhatsApp Abortion Clinic Serv...Abortion Clinic in Springs +27791653574 Springs WhatsApp Abortion Clinic Serv...
Abortion Clinic in Springs +27791653574 Springs WhatsApp Abortion Clinic Serv...mikehavy0
 
挂科办理天主教大学毕业证成绩单一模一样品质
挂科办理天主教大学毕业证成绩单一模一样品质挂科办理天主教大学毕业证成绩单一模一样品质
挂科办理天主教大学毕业证成绩单一模一样品质yzeoq
 
Naer VR: Advanced Research and Usability Testing Project
Naer VR: Advanced Research and Usability Testing ProjectNaer VR: Advanced Research and Usability Testing Project
Naer VR: Advanced Research and Usability Testing Projectbuvanatest
 
如何办理(Birmingham毕业证书)伯明翰大学学院毕业证成绩单本科硕士学位证留信学历认证
如何办理(Birmingham毕业证书)伯明翰大学学院毕业证成绩单本科硕士学位证留信学历认证如何办理(Birmingham毕业证书)伯明翰大学学院毕业证成绩单本科硕士学位证留信学历认证
如何办理(Birmingham毕业证书)伯明翰大学学院毕业证成绩单本科硕士学位证留信学历认证ugzga
 
如何办理(UCL毕业证书)伦敦大学学院毕业证成绩单本科硕士学位证留信学历认证
如何办理(UCL毕业证书)伦敦大学学院毕业证成绩单本科硕士学位证留信学历认证如何办理(UCL毕业证书)伦敦大学学院毕业证成绩单本科硕士学位证留信学历认证
如何办理(UCL毕业证书)伦敦大学学院毕业证成绩单本科硕士学位证留信学历认证ugzga
 
Week 11 Mini-Tasks.pptxjjjjjjjjjjjjjjjjjjjj
Week 11 Mini-Tasks.pptxjjjjjjjjjjjjjjjjjjjjWeek 11 Mini-Tasks.pptxjjjjjjjjjjjjjjjjjjjj
Week 11 Mini-Tasks.pptxjjjjjjjjjjjjjjjjjjjjjoshuaclack73
 
100^%)( KATLEHONG))(*((+27838792658))*))௹ )Abortion Pills for Sale in Doha, D...
100^%)( KATLEHONG))(*((+27838792658))*))௹ )Abortion Pills for Sale in Doha, D...100^%)( KATLEHONG))(*((+27838792658))*))௹ )Abortion Pills for Sale in Doha, D...
100^%)( KATLEHONG))(*((+27838792658))*))௹ )Abortion Pills for Sale in Doha, D...pillahdonald
 
如何办理(Columbia College毕业证书)纽约市哥伦比亚大学毕业证成绩单本科硕士学位证留信学历认证
如何办理(Columbia College毕业证书)纽约市哥伦比亚大学毕业证成绩单本科硕士学位证留信学历认证如何办理(Columbia College毕业证书)纽约市哥伦比亚大学毕业证成绩单本科硕士学位证留信学历认证
如何办理(Columbia College毕业证书)纽约市哥伦比亚大学毕业证成绩单本科硕士学位证留信学历认证ugzga
 
如何办理(ArtEZ毕业证书)ArtEZ艺术学院毕业证成绩单本科硕士学位证留信学历认证
如何办理(ArtEZ毕业证书)ArtEZ艺术学院毕业证成绩单本科硕士学位证留信学历认证如何办理(ArtEZ毕业证书)ArtEZ艺术学院毕业证成绩单本科硕士学位证留信学历认证
如何办理(ArtEZ毕业证书)ArtEZ艺术学院毕业证成绩单本科硕士学位证留信学历认证ugzga
 
NO1 Best Kala Jadu Expert Specialist In Qatar Kala Jadu Expert Specialist In ...
NO1 Best Kala Jadu Expert Specialist In Qatar Kala Jadu Expert Specialist In ...NO1 Best Kala Jadu Expert Specialist In Qatar Kala Jadu Expert Specialist In ...
NO1 Best Kala Jadu Expert Specialist In Qatar Kala Jadu Expert Specialist In ...Amil baba
 

Recently uploaded (20)

NO1 Popular kala jadu karne wale ka contact number kala jadu karne wale baba ...
NO1 Popular kala jadu karne wale ka contact number kala jadu karne wale baba ...NO1 Popular kala jadu karne wale ka contact number kala jadu karne wale baba ...
NO1 Popular kala jadu karne wale ka contact number kala jadu karne wale baba ...
 
Webhost NVME Cloud VPS Hosting1234455678
Webhost NVME Cloud VPS Hosting1234455678Webhost NVME Cloud VPS Hosting1234455678
Webhost NVME Cloud VPS Hosting1234455678
 
And that's about to change! (Service Design Drinks Berlin May 2024)
And that's about to change! (Service Design Drinks Berlin May 2024)And that's about to change! (Service Design Drinks Berlin May 2024)
And that's about to change! (Service Design Drinks Berlin May 2024)
 
BIT Khushi gandhi project.pdf graphic design
BIT Khushi gandhi project.pdf graphic designBIT Khushi gandhi project.pdf graphic design
BIT Khushi gandhi project.pdf graphic design
 
Latest Trends in Home and Building Design
Latest Trends in Home and Building DesignLatest Trends in Home and Building Design
Latest Trends in Home and Building Design
 
NO1 Best Best Amil In Rawalpindi Bangali Baba In Rawalpindi jadu tona karne w...
NO1 Best Best Amil In Rawalpindi Bangali Baba In Rawalpindi jadu tona karne w...NO1 Best Best Amil In Rawalpindi Bangali Baba In Rawalpindi jadu tona karne w...
NO1 Best Best Amil In Rawalpindi Bangali Baba In Rawalpindi jadu tona karne w...
 
Digital Marketing Company in Bangalore.pdf
Digital Marketing Company in Bangalore.pdfDigital Marketing Company in Bangalore.pdf
Digital Marketing Company in Bangalore.pdf
 
NO1 Best Best Black Magic Specialist Near Me Spiritual Healer Powerful Love S...
NO1 Best Best Black Magic Specialist Near Me Spiritual Healer Powerful Love S...NO1 Best Best Black Magic Specialist Near Me Spiritual Healer Powerful Love S...
NO1 Best Best Black Magic Specialist Near Me Spiritual Healer Powerful Love S...
 
Game Pitch- Heroes of Niflheim (a mobile game).pdf
Game Pitch- Heroes of Niflheim (a mobile game).pdfGame Pitch- Heroes of Niflheim (a mobile game).pdf
Game Pitch- Heroes of Niflheim (a mobile game).pdf
 
Spring Summer 26 Colors Trend Book Peclers Paris
Spring Summer 26 Colors Trend Book Peclers ParisSpring Summer 26 Colors Trend Book Peclers Paris
Spring Summer 26 Colors Trend Book Peclers Paris
 
Abortion Clinic in Springs +27791653574 Springs WhatsApp Abortion Clinic Serv...
Abortion Clinic in Springs +27791653574 Springs WhatsApp Abortion Clinic Serv...Abortion Clinic in Springs +27791653574 Springs WhatsApp Abortion Clinic Serv...
Abortion Clinic in Springs +27791653574 Springs WhatsApp Abortion Clinic Serv...
 
挂科办理天主教大学毕业证成绩单一模一样品质
挂科办理天主教大学毕业证成绩单一模一样品质挂科办理天主教大学毕业证成绩单一模一样品质
挂科办理天主教大学毕业证成绩单一模一样品质
 
Naer VR: Advanced Research and Usability Testing Project
Naer VR: Advanced Research and Usability Testing ProjectNaer VR: Advanced Research and Usability Testing Project
Naer VR: Advanced Research and Usability Testing Project
 
如何办理(Birmingham毕业证书)伯明翰大学学院毕业证成绩单本科硕士学位证留信学历认证
如何办理(Birmingham毕业证书)伯明翰大学学院毕业证成绩单本科硕士学位证留信学历认证如何办理(Birmingham毕业证书)伯明翰大学学院毕业证成绩单本科硕士学位证留信学历认证
如何办理(Birmingham毕业证书)伯明翰大学学院毕业证成绩单本科硕士学位证留信学历认证
 
如何办理(UCL毕业证书)伦敦大学学院毕业证成绩单本科硕士学位证留信学历认证
如何办理(UCL毕业证书)伦敦大学学院毕业证成绩单本科硕士学位证留信学历认证如何办理(UCL毕业证书)伦敦大学学院毕业证成绩单本科硕士学位证留信学历认证
如何办理(UCL毕业证书)伦敦大学学院毕业证成绩单本科硕士学位证留信学历认证
 
Week 11 Mini-Tasks.pptxjjjjjjjjjjjjjjjjjjjj
Week 11 Mini-Tasks.pptxjjjjjjjjjjjjjjjjjjjjWeek 11 Mini-Tasks.pptxjjjjjjjjjjjjjjjjjjjj
Week 11 Mini-Tasks.pptxjjjjjjjjjjjjjjjjjjjj
 
100^%)( KATLEHONG))(*((+27838792658))*))௹ )Abortion Pills for Sale in Doha, D...
100^%)( KATLEHONG))(*((+27838792658))*))௹ )Abortion Pills for Sale in Doha, D...100^%)( KATLEHONG))(*((+27838792658))*))௹ )Abortion Pills for Sale in Doha, D...
100^%)( KATLEHONG))(*((+27838792658))*))௹ )Abortion Pills for Sale in Doha, D...
 
如何办理(Columbia College毕业证书)纽约市哥伦比亚大学毕业证成绩单本科硕士学位证留信学历认证
如何办理(Columbia College毕业证书)纽约市哥伦比亚大学毕业证成绩单本科硕士学位证留信学历认证如何办理(Columbia College毕业证书)纽约市哥伦比亚大学毕业证成绩单本科硕士学位证留信学历认证
如何办理(Columbia College毕业证书)纽约市哥伦比亚大学毕业证成绩单本科硕士学位证留信学历认证
 
如何办理(ArtEZ毕业证书)ArtEZ艺术学院毕业证成绩单本科硕士学位证留信学历认证
如何办理(ArtEZ毕业证书)ArtEZ艺术学院毕业证成绩单本科硕士学位证留信学历认证如何办理(ArtEZ毕业证书)ArtEZ艺术学院毕业证成绩单本科硕士学位证留信学历认证
如何办理(ArtEZ毕业证书)ArtEZ艺术学院毕业证成绩单本科硕士学位证留信学历认证
 
NO1 Best Kala Jadu Expert Specialist In Qatar Kala Jadu Expert Specialist In ...
NO1 Best Kala Jadu Expert Specialist In Qatar Kala Jadu Expert Specialist In ...NO1 Best Kala Jadu Expert Specialist In Qatar Kala Jadu Expert Specialist In ...
NO1 Best Kala Jadu Expert Specialist In Qatar Kala Jadu Expert Specialist In ...
 

13785038.ppt

  • 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