SlideShare a Scribd company logo
1 of 18
Momento
Sobia Batool SP21-BSE-031
PRESENTED BY
Design Pattern
Dr. Muhammad Farhan
PRESENTED TO
Table of
Content
Introduction
1 Problem
2
Solution
3 Structure
4
#Pseudocode
5 Applicability
6
Pros and Cons
7
Relation Wwith Other
Patterns
8
Memento is a behavioral design pattern
that lets you save and restore the
previous state of an object without
revealing the details of its
implementation.
Introduction
Problem
Imagine that you’re creating a text editor
app. In addition to simple text editing, your
editor can format text, insert inline images,
etc.
In implementing undo functionality, the
chosen approach involves recording the
state of all objects before operations and
saving it for later retrieval. However,
creating state snapshots becomes
challenging due to restrictions on
accessing private fields in objects,
hindering the straightforward copying of
values into storage.
Before executing an operation, the app
saves a snapshot of the objects’ state,
which can later be used to restore objects
to their previous state.
Problem (Continue)
Assuming objects behave openly to allow state
snapshots, it facilitates creating snapshots but
raises issues when modifying editor classes in
the future. Copying private object states
presents challenges, and creating snapshots
involves exposing all editor states, making
classes dependent on changes. This dilemma—
exposing internal details and making classes
fragile or restricting access and hindering
snapshot production—seems like a deadlock in
implementing the "undo" feature, prompting
exploration of alternative solutions.
Solution
The Memento pattern delegates creating the state snapshots to the actual owner of
that state, the originator object. Hence, instead of other objects trying to copy the
editor’s state from the “outside,” the editor class itself can make the snapshot since it
has full access to its own state.
The pattern suggests storing the copy of the object’s state in a special object called
memento.
Such a restrictive policy lets you store mementos inside other objects, usually called
caretakers.
Solution
The originator has full access to the
memento, whereas the caretaker can
only access the metadata.
Structure
The classic implementation of the
pattern relies on support for nested
classes, available in many popular
programming languages (such as C++,
C#, and Java).
Implementation based on nested classes
Structure
There’s an alternative implementation,
suitable for programming languages
that don’t support nested classes
(yeah, PHP, I’m talking about you).
Implementation based on an intermediate interface
Structure
There’s another implementation which
is useful when you don’t want to leave
even the slightest chance of other
classes accessing the state of the
originator through the memento.
Implementation with even stricter encapsulation
# Pseudocode
This example uses the Memento pattern alongside the Command pattern for storing
snapshots of the complex text editor’s state and restoring an earlier state from these
snapshots when needed.
Saving snapshots of the text editor’s state
# Pseudocode
/ The originator holds some important data that may change over
// time. It also defines a method for saving its state inside a
// memento and another method for restoring the state from it.
class Editor is
private field text, curX, curY, selectionWidth
method setText(text) is
this.text = text
method setCursor(x, y) is
this.curX = x
this.curY = y
method setSelectionWidth(width) is
this.selectionWidth = width
// Saves the current state inside a memento.
method createSnapshot():Snapshot is
// Memento is an immutable object; that's why the
// originator passes its state to the memento's
// constructor parameters.
return new Snapshot(this, text, curX, curY, selectionWidth)
# Pseudocode
// The memento class stores the past state of the editor.
class Snapshot is
private field editor: Editor
private field text, curX, curY, selectionWidth
constructor Snapshot(editor, text, curX, curY, selectionWidth)
is
this.editor = editor
this.text = text
this.curX = x
this.curY = y
this.selectionWidth = selectionWidth
// At some point, a previous state of the editor can be
// restored using a memento object.
method restore() is
editor.setText(text)
editor.setCursor(curX, curY)
editor.setSelectionWidth(selectionWidth)
# Pseudocode
// A command object can act as a caretaker. In that case, the
// command gets a memento just before it changes the
// originator's state. When undo is requested, it restores the
// originator's state from a memento.
class Command is
private field backup: Snapshot
method makeBackup() is
backup = editor.createSnapshot()
method undo() is
if (backup != null)
backup.restore()
// ...
Applicability
Use the Memento
pattern when you want
to produce snapshots
of the object’s state to
be able to restore a
previous state of the
object.
Use the pattern when direct
access to the object’s
fields/getters/setters violates its
encapsulation.
Pros and Cons
The app might consume lots of RAM if
clients create mementos too often.
Caretakers should track the originator’s
lifecycle to be able to destroy obsolete
mementos.
Most dynamic programming languages,
such as PHP, Python and JavaScript, can’t
guarantee that the state within the
memento stays untouched.
Pros Cons
You can produce snapshots of the object’s
state without violating its encapsulation.
You can simplify the originator’s code by
letting the caretaker maintain the history
of the originator’s state.
Relation With Other Patterns
• You can use Command and Memento together when implementing “undo”. In
this case, commands are responsible for performing various operations over a
target object, while mementos save the state of that object just before a
command gets executed.
• You can use Memento along with Iterator to capture the current iteration state
and roll it back if necessary.
• Sometimes Prototype can be a simpler alternative to Memento. This works if the
object, the state of which you want to store in the history, is fairly straightforward
and doesn’t have links to external resources, or the links are easy to re-establish.
Thank You

More Related Content

Similar to Momento Design Pattern- A brief Understanding

Lesson10 behavioral patterns
Lesson10 behavioral patternsLesson10 behavioral patterns
Lesson10 behavioral patternsOktJona
 
Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react jsStephieJohn
 
P Training Presentation
P Training PresentationP Training Presentation
P Training PresentationGaurav Tyagi
 
Eclipse Training - Standard Extension Points and APIs
Eclipse Training - Standard Extension Points and APIsEclipse Training - Standard Extension Points and APIs
Eclipse Training - Standard Extension Points and APIsLuca D'Onofrio
 
DSC - Shared Preferences and Room
DSC - Shared Preferences and RoomDSC - Shared Preferences and Room
DSC - Shared Preferences and RoomAgustinus Theodorus
 
Nt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language AnalysisNt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language AnalysisNicole Gomez
 
Spring IOC advantages and developing spring application sample
Spring IOC advantages and developing spring application sample Spring IOC advantages and developing spring application sample
Spring IOC advantages and developing spring application sample Sunil kumar Mohanty
 
Rapid Prototyping with TurboGears2
Rapid Prototyping with TurboGears2Rapid Prototyping with TurboGears2
Rapid Prototyping with TurboGears2Alessandro Molina
 
WPF Windows Presentation Foundation A detailed overview Version1.2
WPF Windows Presentation Foundation A detailed overview Version1.2WPF Windows Presentation Foundation A detailed overview Version1.2
WPF Windows Presentation Foundation A detailed overview Version1.2Shahzad
 
4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPTAjay Chimmani
 
02 Hibernate Introduction
02 Hibernate Introduction02 Hibernate Introduction
02 Hibernate IntroductionRanjan Kumar
 

Similar to Momento Design Pattern- A brief Understanding (20)

Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Lesson10 behavioral patterns
Lesson10 behavioral patternsLesson10 behavioral patterns
Lesson10 behavioral patterns
 
Code Quality Management iOS
Code Quality Management iOSCode Quality Management iOS
Code Quality Management iOS
 
13785038.ppt
13785038.ppt13785038.ppt
13785038.ppt
 
Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react js
 
P Training Presentation
P Training PresentationP Training Presentation
P Training Presentation
 
Persistence
PersistencePersistence
Persistence
 
Redux essentials
Redux essentialsRedux essentials
Redux essentials
 
Eclipse Training - Standard Extension Points and APIs
Eclipse Training - Standard Extension Points and APIsEclipse Training - Standard Extension Points and APIs
Eclipse Training - Standard Extension Points and APIs
 
DSC - Shared Preferences and Room
DSC - Shared Preferences and RoomDSC - Shared Preferences and Room
DSC - Shared Preferences and Room
 
Nt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language AnalysisNt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language Analysis
 
Spring IOC advantages and developing spring application sample
Spring IOC advantages and developing spring application sample Spring IOC advantages and developing spring application sample
Spring IOC advantages and developing spring application sample
 
Hello Android
Hello AndroidHello Android
Hello Android
 
Jvm internal detail
Jvm internal detailJvm internal detail
Jvm internal detail
 
Rapid Prototyping with TurboGears2
Rapid Prototyping with TurboGears2Rapid Prototyping with TurboGears2
Rapid Prototyping with TurboGears2
 
WPF Windows Presentation Foundation A detailed overview Version1.2
WPF Windows Presentation Foundation A detailed overview Version1.2WPF Windows Presentation Foundation A detailed overview Version1.2
WPF Windows Presentation Foundation A detailed overview Version1.2
 
TY.BSc.IT Java QB U6
TY.BSc.IT Java QB U6TY.BSc.IT Java QB U6
TY.BSc.IT Java QB U6
 
4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT
 
Synopsis
SynopsisSynopsis
Synopsis
 
02 Hibernate Introduction
02 Hibernate Introduction02 Hibernate Introduction
02 Hibernate Introduction
 

Recently uploaded

Chapter 19_DDA_TOD Policy_First Draft 2012.pdf
Chapter 19_DDA_TOD Policy_First Draft 2012.pdfChapter 19_DDA_TOD Policy_First Draft 2012.pdf
Chapter 19_DDA_TOD Policy_First Draft 2012.pdfParomita Roy
 
The history of music videos a level presentation
The history of music videos a level presentationThe history of music videos a level presentation
The history of music videos a level presentationamedia6
 
(AISHA) Ambegaon Khurd Call Girls Just Call 7001035870 [ Cash on Delivery ] P...
(AISHA) Ambegaon Khurd Call Girls Just Call 7001035870 [ Cash on Delivery ] P...(AISHA) Ambegaon Khurd Call Girls Just Call 7001035870 [ Cash on Delivery ] P...
(AISHA) Ambegaon Khurd Call Girls Just Call 7001035870 [ Cash on Delivery ] P...ranjana rawat
 
VVIP Pune Call Girls Hadapsar (7001035870) Pune Escorts Nearby with Complete ...
VVIP Pune Call Girls Hadapsar (7001035870) Pune Escorts Nearby with Complete ...VVIP Pune Call Girls Hadapsar (7001035870) Pune Escorts Nearby with Complete ...
VVIP Pune Call Girls Hadapsar (7001035870) Pune Escorts Nearby with Complete ...Call Girls in Nagpur High Profile
 
AMBER GRAIN EMBROIDERY | Growing folklore elements | Root-based materials, w...
AMBER GRAIN EMBROIDERY | Growing folklore elements |  Root-based materials, w...AMBER GRAIN EMBROIDERY | Growing folklore elements |  Root-based materials, w...
AMBER GRAIN EMBROIDERY | Growing folklore elements | Root-based materials, w...BarusRa
 
Editorial design Magazine design project.pdf
Editorial design Magazine design project.pdfEditorial design Magazine design project.pdf
Editorial design Magazine design project.pdftbatkhuu1
 
Peaches App development presentation deck
Peaches App development presentation deckPeaches App development presentation deck
Peaches App development presentation decktbatkhuu1
 
Presentation.pptx about blender what is blender
Presentation.pptx about blender what is blenderPresentation.pptx about blender what is blender
Presentation.pptx about blender what is blenderUbaidurrehman997675
 
DragonBall PowerPoint Template for demo.pptx
DragonBall PowerPoint Template for demo.pptxDragonBall PowerPoint Template for demo.pptx
DragonBall PowerPoint Template for demo.pptxmirandajeremy200221
 
Kindergarten Assessment Questions Via LessonUp
Kindergarten Assessment Questions Via LessonUpKindergarten Assessment Questions Via LessonUp
Kindergarten Assessment Questions Via LessonUpmainac1
 
Best VIP Call Girls Noida Sector 47 Call Me: 8448380779
Best VIP Call Girls Noida Sector 47 Call Me: 8448380779Best VIP Call Girls Noida Sector 47 Call Me: 8448380779
Best VIP Call Girls Noida Sector 47 Call Me: 8448380779Delhi Call girls
 
Captivating Charm: Exploring Marseille's Hillside Villas with Our 3D Architec...
Captivating Charm: Exploring Marseille's Hillside Villas with Our 3D Architec...Captivating Charm: Exploring Marseille's Hillside Villas with Our 3D Architec...
Captivating Charm: Exploring Marseille's Hillside Villas with Our 3D Architec...Yantram Animation Studio Corporation
 
VIP Russian Call Girls in Saharanpur Deepika 8250192130 Independent Escort Se...
VIP Russian Call Girls in Saharanpur Deepika 8250192130 Independent Escort Se...VIP Russian Call Girls in Saharanpur Deepika 8250192130 Independent Escort Se...
VIP Russian Call Girls in Saharanpur Deepika 8250192130 Independent Escort Se...Suhani Kapoor
 
CALL ON ➥8923113531 🔝Call Girls Kalyanpur Lucknow best Female service 🧵
CALL ON ➥8923113531 🔝Call Girls Kalyanpur Lucknow best Female service  🧵CALL ON ➥8923113531 🔝Call Girls Kalyanpur Lucknow best Female service  🧵
CALL ON ➥8923113531 🔝Call Girls Kalyanpur Lucknow best Female service 🧵anilsa9823
 
NO1 Trending kala jadu Love Marriage Black Magic Punjab Powerful Black Magic ...
NO1 Trending kala jadu Love Marriage Black Magic Punjab Powerful Black Magic ...NO1 Trending kala jadu Love Marriage Black Magic Punjab Powerful Black Magic ...
NO1 Trending kala jadu Love Marriage Black Magic Punjab Powerful Black Magic ...Amil baba
 
Kala jadu for love marriage | Real amil baba | Famous amil baba | kala jadu n...
Kala jadu for love marriage | Real amil baba | Famous amil baba | kala jadu n...Kala jadu for love marriage | Real amil baba | Famous amil baba | kala jadu n...
Kala jadu for love marriage | Real amil baba | Famous amil baba | kala jadu n...babafaisel
 
Night 7k to 12k Call Girl Price Ahmedabad 👉 BOOK NOW 8617697112 👈 ♀️ night gi...
Night 7k to 12k Call Girl Price Ahmedabad 👉 BOOK NOW 8617697112 👈 ♀️ night gi...Night 7k to 12k Call Girl Price Ahmedabad 👉 BOOK NOW 8617697112 👈 ♀️ night gi...
Night 7k to 12k Call Girl Price Ahmedabad 👉 BOOK NOW 8617697112 👈 ♀️ night gi...Call girls in Ahmedabad High profile
 
Verified Trusted Call Girls Adugodi💘 9352852248 Good Looking standard Profil...
Verified Trusted Call Girls Adugodi💘 9352852248  Good Looking standard Profil...Verified Trusted Call Girls Adugodi💘 9352852248  Good Looking standard Profil...
Verified Trusted Call Girls Adugodi💘 9352852248 Good Looking standard Profil...kumaririma588
 
CBD Belapur Individual Call Girls In 08976425520 Panvel Only Genuine Call Girls
CBD Belapur Individual Call Girls In 08976425520 Panvel Only Genuine Call GirlsCBD Belapur Individual Call Girls In 08976425520 Panvel Only Genuine Call Girls
CBD Belapur Individual Call Girls In 08976425520 Panvel Only Genuine Call Girlsmodelanjalisharma4
 

Recently uploaded (20)

Chapter 19_DDA_TOD Policy_First Draft 2012.pdf
Chapter 19_DDA_TOD Policy_First Draft 2012.pdfChapter 19_DDA_TOD Policy_First Draft 2012.pdf
Chapter 19_DDA_TOD Policy_First Draft 2012.pdf
 
B. Smith. (Architectural Portfolio.).pdf
B. Smith. (Architectural Portfolio.).pdfB. Smith. (Architectural Portfolio.).pdf
B. Smith. (Architectural Portfolio.).pdf
 
The history of music videos a level presentation
The history of music videos a level presentationThe history of music videos a level presentation
The history of music videos a level presentation
 
(AISHA) Ambegaon Khurd Call Girls Just Call 7001035870 [ Cash on Delivery ] P...
(AISHA) Ambegaon Khurd Call Girls Just Call 7001035870 [ Cash on Delivery ] P...(AISHA) Ambegaon Khurd Call Girls Just Call 7001035870 [ Cash on Delivery ] P...
(AISHA) Ambegaon Khurd Call Girls Just Call 7001035870 [ Cash on Delivery ] P...
 
VVIP Pune Call Girls Hadapsar (7001035870) Pune Escorts Nearby with Complete ...
VVIP Pune Call Girls Hadapsar (7001035870) Pune Escorts Nearby with Complete ...VVIP Pune Call Girls Hadapsar (7001035870) Pune Escorts Nearby with Complete ...
VVIP Pune Call Girls Hadapsar (7001035870) Pune Escorts Nearby with Complete ...
 
AMBER GRAIN EMBROIDERY | Growing folklore elements | Root-based materials, w...
AMBER GRAIN EMBROIDERY | Growing folklore elements |  Root-based materials, w...AMBER GRAIN EMBROIDERY | Growing folklore elements |  Root-based materials, w...
AMBER GRAIN EMBROIDERY | Growing folklore elements | Root-based materials, w...
 
Editorial design Magazine design project.pdf
Editorial design Magazine design project.pdfEditorial design Magazine design project.pdf
Editorial design Magazine design project.pdf
 
Peaches App development presentation deck
Peaches App development presentation deckPeaches App development presentation deck
Peaches App development presentation deck
 
Presentation.pptx about blender what is blender
Presentation.pptx about blender what is blenderPresentation.pptx about blender what is blender
Presentation.pptx about blender what is blender
 
DragonBall PowerPoint Template for demo.pptx
DragonBall PowerPoint Template for demo.pptxDragonBall PowerPoint Template for demo.pptx
DragonBall PowerPoint Template for demo.pptx
 
Kindergarten Assessment Questions Via LessonUp
Kindergarten Assessment Questions Via LessonUpKindergarten Assessment Questions Via LessonUp
Kindergarten Assessment Questions Via LessonUp
 
Best VIP Call Girls Noida Sector 47 Call Me: 8448380779
Best VIP Call Girls Noida Sector 47 Call Me: 8448380779Best VIP Call Girls Noida Sector 47 Call Me: 8448380779
Best VIP Call Girls Noida Sector 47 Call Me: 8448380779
 
Captivating Charm: Exploring Marseille's Hillside Villas with Our 3D Architec...
Captivating Charm: Exploring Marseille's Hillside Villas with Our 3D Architec...Captivating Charm: Exploring Marseille's Hillside Villas with Our 3D Architec...
Captivating Charm: Exploring Marseille's Hillside Villas with Our 3D Architec...
 
VIP Russian Call Girls in Saharanpur Deepika 8250192130 Independent Escort Se...
VIP Russian Call Girls in Saharanpur Deepika 8250192130 Independent Escort Se...VIP Russian Call Girls in Saharanpur Deepika 8250192130 Independent Escort Se...
VIP Russian Call Girls in Saharanpur Deepika 8250192130 Independent Escort Se...
 
CALL ON ➥8923113531 🔝Call Girls Kalyanpur Lucknow best Female service 🧵
CALL ON ➥8923113531 🔝Call Girls Kalyanpur Lucknow best Female service  🧵CALL ON ➥8923113531 🔝Call Girls Kalyanpur Lucknow best Female service  🧵
CALL ON ➥8923113531 🔝Call Girls Kalyanpur Lucknow best Female service 🧵
 
NO1 Trending kala jadu Love Marriage Black Magic Punjab Powerful Black Magic ...
NO1 Trending kala jadu Love Marriage Black Magic Punjab Powerful Black Magic ...NO1 Trending kala jadu Love Marriage Black Magic Punjab Powerful Black Magic ...
NO1 Trending kala jadu Love Marriage Black Magic Punjab Powerful Black Magic ...
 
Kala jadu for love marriage | Real amil baba | Famous amil baba | kala jadu n...
Kala jadu for love marriage | Real amil baba | Famous amil baba | kala jadu n...Kala jadu for love marriage | Real amil baba | Famous amil baba | kala jadu n...
Kala jadu for love marriage | Real amil baba | Famous amil baba | kala jadu n...
 
Night 7k to 12k Call Girl Price Ahmedabad 👉 BOOK NOW 8617697112 👈 ♀️ night gi...
Night 7k to 12k Call Girl Price Ahmedabad 👉 BOOK NOW 8617697112 👈 ♀️ night gi...Night 7k to 12k Call Girl Price Ahmedabad 👉 BOOK NOW 8617697112 👈 ♀️ night gi...
Night 7k to 12k Call Girl Price Ahmedabad 👉 BOOK NOW 8617697112 👈 ♀️ night gi...
 
Verified Trusted Call Girls Adugodi💘 9352852248 Good Looking standard Profil...
Verified Trusted Call Girls Adugodi💘 9352852248  Good Looking standard Profil...Verified Trusted Call Girls Adugodi💘 9352852248  Good Looking standard Profil...
Verified Trusted Call Girls Adugodi💘 9352852248 Good Looking standard Profil...
 
CBD Belapur Individual Call Girls In 08976425520 Panvel Only Genuine Call Girls
CBD Belapur Individual Call Girls In 08976425520 Panvel Only Genuine Call GirlsCBD Belapur Individual Call Girls In 08976425520 Panvel Only Genuine Call Girls
CBD Belapur Individual Call Girls In 08976425520 Panvel Only Genuine Call Girls
 

Momento Design Pattern- A brief Understanding

  • 1. Momento Sobia Batool SP21-BSE-031 PRESENTED BY Design Pattern Dr. Muhammad Farhan PRESENTED TO
  • 2. Table of Content Introduction 1 Problem 2 Solution 3 Structure 4 #Pseudocode 5 Applicability 6 Pros and Cons 7 Relation Wwith Other Patterns 8
  • 3. Memento is a behavioral design pattern that lets you save and restore the previous state of an object without revealing the details of its implementation. Introduction
  • 4. Problem Imagine that you’re creating a text editor app. In addition to simple text editing, your editor can format text, insert inline images, etc. In implementing undo functionality, the chosen approach involves recording the state of all objects before operations and saving it for later retrieval. However, creating state snapshots becomes challenging due to restrictions on accessing private fields in objects, hindering the straightforward copying of values into storage. Before executing an operation, the app saves a snapshot of the objects’ state, which can later be used to restore objects to their previous state.
  • 5. Problem (Continue) Assuming objects behave openly to allow state snapshots, it facilitates creating snapshots but raises issues when modifying editor classes in the future. Copying private object states presents challenges, and creating snapshots involves exposing all editor states, making classes dependent on changes. This dilemma— exposing internal details and making classes fragile or restricting access and hindering snapshot production—seems like a deadlock in implementing the "undo" feature, prompting exploration of alternative solutions.
  • 6. Solution The Memento pattern delegates creating the state snapshots to the actual owner of that state, the originator object. Hence, instead of other objects trying to copy the editor’s state from the “outside,” the editor class itself can make the snapshot since it has full access to its own state. The pattern suggests storing the copy of the object’s state in a special object called memento. Such a restrictive policy lets you store mementos inside other objects, usually called caretakers.
  • 7. Solution The originator has full access to the memento, whereas the caretaker can only access the metadata.
  • 8. Structure The classic implementation of the pattern relies on support for nested classes, available in many popular programming languages (such as C++, C#, and Java). Implementation based on nested classes
  • 9. Structure There’s an alternative implementation, suitable for programming languages that don’t support nested classes (yeah, PHP, I’m talking about you). Implementation based on an intermediate interface
  • 10. Structure There’s another implementation which is useful when you don’t want to leave even the slightest chance of other classes accessing the state of the originator through the memento. Implementation with even stricter encapsulation
  • 11. # Pseudocode This example uses the Memento pattern alongside the Command pattern for storing snapshots of the complex text editor’s state and restoring an earlier state from these snapshots when needed. Saving snapshots of the text editor’s state
  • 12. # Pseudocode / The originator holds some important data that may change over // time. It also defines a method for saving its state inside a // memento and another method for restoring the state from it. class Editor is private field text, curX, curY, selectionWidth method setText(text) is this.text = text method setCursor(x, y) is this.curX = x this.curY = y method setSelectionWidth(width) is this.selectionWidth = width // Saves the current state inside a memento. method createSnapshot():Snapshot is // Memento is an immutable object; that's why the // originator passes its state to the memento's // constructor parameters. return new Snapshot(this, text, curX, curY, selectionWidth)
  • 13. # Pseudocode // The memento class stores the past state of the editor. class Snapshot is private field editor: Editor private field text, curX, curY, selectionWidth constructor Snapshot(editor, text, curX, curY, selectionWidth) is this.editor = editor this.text = text this.curX = x this.curY = y this.selectionWidth = selectionWidth // At some point, a previous state of the editor can be // restored using a memento object. method restore() is editor.setText(text) editor.setCursor(curX, curY) editor.setSelectionWidth(selectionWidth)
  • 14. # Pseudocode // A command object can act as a caretaker. In that case, the // command gets a memento just before it changes the // originator's state. When undo is requested, it restores the // originator's state from a memento. class Command is private field backup: Snapshot method makeBackup() is backup = editor.createSnapshot() method undo() is if (backup != null) backup.restore() // ...
  • 15. Applicability Use the Memento pattern when you want to produce snapshots of the object’s state to be able to restore a previous state of the object. Use the pattern when direct access to the object’s fields/getters/setters violates its encapsulation.
  • 16. Pros and Cons The app might consume lots of RAM if clients create mementos too often. Caretakers should track the originator’s lifecycle to be able to destroy obsolete mementos. Most dynamic programming languages, such as PHP, Python and JavaScript, can’t guarantee that the state within the memento stays untouched. Pros Cons You can produce snapshots of the object’s state without violating its encapsulation. You can simplify the originator’s code by letting the caretaker maintain the history of the originator’s state.
  • 17. Relation With Other Patterns • You can use Command and Memento together when implementing “undo”. In this case, commands are responsible for performing various operations over a target object, while mementos save the state of that object just before a command gets executed. • You can use Memento along with Iterator to capture the current iteration state and roll it back if necessary. • Sometimes Prototype can be a simpler alternative to Memento. This works if the object, the state of which you want to store in the history, is fairly straightforward and doesn’t have links to external resources, or the links are easy to re-establish.