SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Ähnlich wie 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
 

Ähnlich wie 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
 

Kürzlich hochgeladen

call girls in Vasundhra (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝...
call girls in Vasundhra (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝...call girls in Vasundhra (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝...
call girls in Vasundhra (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝...Delhi Call girls
 
Top Rated Pune Call Girls Koregaon Park ⟟ 6297143586 ⟟ Call Me For Genuine S...
Top Rated  Pune Call Girls Koregaon Park ⟟ 6297143586 ⟟ Call Me For Genuine S...Top Rated  Pune Call Girls Koregaon Park ⟟ 6297143586 ⟟ Call Me For Genuine S...
Top Rated Pune Call Girls Koregaon Park ⟟ 6297143586 ⟟ Call Me For Genuine S...Call Girls in Nagpur High Profile
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756dollysharma2066
 
SD_The MATATAG Curriculum Training Design.pptx
SD_The MATATAG Curriculum Training Design.pptxSD_The MATATAG Curriculum Training Design.pptx
SD_The MATATAG Curriculum Training Design.pptxjanettecruzeiro1
 
VVIP CALL GIRLS Lucknow 💓 Lucknow < Renuka Sharma > 7877925207 Escorts Service
VVIP CALL GIRLS Lucknow 💓 Lucknow < Renuka Sharma > 7877925207 Escorts ServiceVVIP CALL GIRLS Lucknow 💓 Lucknow < Renuka Sharma > 7877925207 Escorts Service
VVIP CALL GIRLS Lucknow 💓 Lucknow < Renuka Sharma > 7877925207 Escorts Servicearoranaina404
 
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
 
Escorts Service Basapura ☎ 7737669865☎ Book Your One night Stand (Bangalore)
Escorts Service Basapura ☎ 7737669865☎ Book Your One night Stand (Bangalore)Escorts Service Basapura ☎ 7737669865☎ Book Your One night Stand (Bangalore)
Escorts Service Basapura ☎ 7737669865☎ Book Your One night Stand (Bangalore)amitlee9823
 
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
 
Stark Industries Marketing Plan (1).pptx
Stark Industries Marketing Plan (1).pptxStark Industries Marketing Plan (1).pptx
Stark Industries Marketing Plan (1).pptxjeswinjees
 
RT Nagar Call Girls Service: 🍓 7737669865 🍓 High Profile Model Escorts | Bang...
RT Nagar Call Girls Service: 🍓 7737669865 🍓 High Profile Model Escorts | Bang...RT Nagar Call Girls Service: 🍓 7737669865 🍓 High Profile Model Escorts | Bang...
RT Nagar Call Girls Service: 🍓 7737669865 🍓 High Profile Model Escorts | Bang...amitlee9823
 
Escorts Service Nagavara ☎ 7737669865☎ Book Your One night Stand (Bangalore)
Escorts Service Nagavara ☎ 7737669865☎ Book Your One night Stand (Bangalore)Escorts Service Nagavara ☎ 7737669865☎ Book Your One night Stand (Bangalore)
Escorts Service Nagavara ☎ 7737669865☎ Book Your One night Stand (Bangalore)amitlee9823
 
Tapestry Clothing Brands: Collapsing the Funnel
Tapestry Clothing Brands: Collapsing the FunnelTapestry Clothing Brands: Collapsing the Funnel
Tapestry Clothing Brands: Collapsing the Funneljen_giacalone
 
Call Girls Basavanagudi Just Call 👗 7737669865 👗 Top Class Call Girl Service ...
Call Girls Basavanagudi Just Call 👗 7737669865 👗 Top Class Call Girl Service ...Call Girls Basavanagudi Just Call 👗 7737669865 👗 Top Class Call Girl Service ...
Call Girls Basavanagudi Just Call 👗 7737669865 👗 Top Class Call Girl Service ...amitlee9823
 
UI:UX Design and Empowerment Strategies for Underprivileged Transgender Indiv...
UI:UX Design and Empowerment Strategies for Underprivileged Transgender Indiv...UI:UX Design and Empowerment Strategies for Underprivileged Transgender Indiv...
UI:UX Design and Empowerment Strategies for Underprivileged Transgender Indiv...RitikaRoy32
 
DragonBall PowerPoint Template for demo.pptx
DragonBall PowerPoint Template for demo.pptxDragonBall PowerPoint Template for demo.pptx
DragonBall PowerPoint Template for demo.pptxmirandajeremy200221
 
VIP Model Call Girls Kalyani Nagar ( Pune ) Call ON 8005736733 Starting From ...
VIP Model Call Girls Kalyani Nagar ( Pune ) Call ON 8005736733 Starting From ...VIP Model Call Girls Kalyani Nagar ( Pune ) Call ON 8005736733 Starting From ...
VIP Model Call Girls Kalyani Nagar ( Pune ) Call ON 8005736733 Starting From ...SUHANI PANDEY
 
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_Canvas_of_Creative_Mastery_Newsletter_April_2024_Version.pdf
The_Canvas_of_Creative_Mastery_Newsletter_April_2024_Version.pdfThe_Canvas_of_Creative_Mastery_Newsletter_April_2024_Version.pdf
The_Canvas_of_Creative_Mastery_Newsletter_April_2024_Version.pdfAmirYakdi
 
2-tool presenthdbdbdbdbddhdhddation.pptx
2-tool presenthdbdbdbdbddhdhddation.pptx2-tool presenthdbdbdbdbddhdhddation.pptx
2-tool presenthdbdbdbdbddhdhddation.pptxsuhanimunjal27
 
(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
 

Kürzlich hochgeladen (20)

call girls in Vasundhra (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝...
call girls in Vasundhra (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝...call girls in Vasundhra (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝...
call girls in Vasundhra (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝...
 
Top Rated Pune Call Girls Koregaon Park ⟟ 6297143586 ⟟ Call Me For Genuine S...
Top Rated  Pune Call Girls Koregaon Park ⟟ 6297143586 ⟟ Call Me For Genuine S...Top Rated  Pune Call Girls Koregaon Park ⟟ 6297143586 ⟟ Call Me For Genuine S...
Top Rated Pune Call Girls Koregaon Park ⟟ 6297143586 ⟟ Call Me For Genuine S...
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
SD_The MATATAG Curriculum Training Design.pptx
SD_The MATATAG Curriculum Training Design.pptxSD_The MATATAG Curriculum Training Design.pptx
SD_The MATATAG Curriculum Training Design.pptx
 
VVIP CALL GIRLS Lucknow 💓 Lucknow < Renuka Sharma > 7877925207 Escorts Service
VVIP CALL GIRLS Lucknow 💓 Lucknow < Renuka Sharma > 7877925207 Escorts ServiceVVIP CALL GIRLS Lucknow 💓 Lucknow < Renuka Sharma > 7877925207 Escorts Service
VVIP CALL GIRLS Lucknow 💓 Lucknow < Renuka Sharma > 7877925207 Escorts Service
 
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...
 
Escorts Service Basapura ☎ 7737669865☎ Book Your One night Stand (Bangalore)
Escorts Service Basapura ☎ 7737669865☎ Book Your One night Stand (Bangalore)Escorts Service Basapura ☎ 7737669865☎ Book Your One night Stand (Bangalore)
Escorts Service Basapura ☎ 7737669865☎ Book Your One night Stand (Bangalore)
 
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 ...
 
Stark Industries Marketing Plan (1).pptx
Stark Industries Marketing Plan (1).pptxStark Industries Marketing Plan (1).pptx
Stark Industries Marketing Plan (1).pptx
 
RT Nagar Call Girls Service: 🍓 7737669865 🍓 High Profile Model Escorts | Bang...
RT Nagar Call Girls Service: 🍓 7737669865 🍓 High Profile Model Escorts | Bang...RT Nagar Call Girls Service: 🍓 7737669865 🍓 High Profile Model Escorts | Bang...
RT Nagar Call Girls Service: 🍓 7737669865 🍓 High Profile Model Escorts | Bang...
 
Escorts Service Nagavara ☎ 7737669865☎ Book Your One night Stand (Bangalore)
Escorts Service Nagavara ☎ 7737669865☎ Book Your One night Stand (Bangalore)Escorts Service Nagavara ☎ 7737669865☎ Book Your One night Stand (Bangalore)
Escorts Service Nagavara ☎ 7737669865☎ Book Your One night Stand (Bangalore)
 
Tapestry Clothing Brands: Collapsing the Funnel
Tapestry Clothing Brands: Collapsing the FunnelTapestry Clothing Brands: Collapsing the Funnel
Tapestry Clothing Brands: Collapsing the Funnel
 
Call Girls Basavanagudi Just Call 👗 7737669865 👗 Top Class Call Girl Service ...
Call Girls Basavanagudi Just Call 👗 7737669865 👗 Top Class Call Girl Service ...Call Girls Basavanagudi Just Call 👗 7737669865 👗 Top Class Call Girl Service ...
Call Girls Basavanagudi Just Call 👗 7737669865 👗 Top Class Call Girl Service ...
 
UI:UX Design and Empowerment Strategies for Underprivileged Transgender Indiv...
UI:UX Design and Empowerment Strategies for Underprivileged Transgender Indiv...UI:UX Design and Empowerment Strategies for Underprivileged Transgender Indiv...
UI:UX Design and Empowerment Strategies for Underprivileged Transgender Indiv...
 
DragonBall PowerPoint Template for demo.pptx
DragonBall PowerPoint Template for demo.pptxDragonBall PowerPoint Template for demo.pptx
DragonBall PowerPoint Template for demo.pptx
 
VIP Model Call Girls Kalyani Nagar ( Pune ) Call ON 8005736733 Starting From ...
VIP Model Call Girls Kalyani Nagar ( Pune ) Call ON 8005736733 Starting From ...VIP Model Call Girls Kalyani Nagar ( Pune ) Call ON 8005736733 Starting From ...
VIP Model Call Girls Kalyani Nagar ( Pune ) Call ON 8005736733 Starting From ...
 
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
 
The_Canvas_of_Creative_Mastery_Newsletter_April_2024_Version.pdf
The_Canvas_of_Creative_Mastery_Newsletter_April_2024_Version.pdfThe_Canvas_of_Creative_Mastery_Newsletter_April_2024_Version.pdf
The_Canvas_of_Creative_Mastery_Newsletter_April_2024_Version.pdf
 
2-tool presenthdbdbdbdbddhdhddation.pptx
2-tool presenthdbdbdbdbddhdhddation.pptx2-tool presenthdbdbdbdbddhdhddation.pptx
2-tool presenthdbdbdbdbddhdhddation.pptx
 
(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...
 

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.