SlideShare a Scribd company logo
1 of 13
Download to read offline
SWIFT
Memento
Bill Kim(김정훈) | ibillkim@gmail.com
목차
•Memento
•Structure
•Implementation
•References
Memento
Memento(메멘토) 패턴은 객체의 상태를 저장하고 복원할 수 있는
행동 디자인 패턴입니다.
기본 오리지날 객체는 본래의 기능에만 충실하고 상태 정보에 대한
관리를 메멘토 객체에게 전담하여 상태를 저장하고 복원할 수 있게
한다.
Structure
Memento 패턴을 UML로 도식화하면 아래와 같습니다.
Structure
Originator : 상태값을 가지고 있고 객체의 본연의 기능만을 수행
하며 저장 및 복원에 대한 작업은 Memento 객체에게 넘기는 객체
Memento : Originator 객체의 스냅샷 역할을 하는 값 객체이다.
메멘토 데이터는 생성장를 통해서 한번만 전달하는 것이 일반적입
니다.
ConcreteMemento : Memento 객체를 상속받아 메멘토 객체가
가진 데이터에 대한 초기화를 진행하는 클래스 객체
Caretaker(Client) : Originator 객체에 대한 상태가 언제 바뀌
고 저장되었는지를 알고 있는 객체, 또한 스냅샷 리스트를 가지고 있
고 복원을 할 경우 가장 최상위의 Originator 상태로 복원을 진행
하는 객체
Implementation
구체적인 구현에 대해서 소스 코드를 통하여 살펴봅니다.
class Originator {
private var state: String
init(state: String) {
self.state = state
print("Originator: My initial state is: (state)")
}
func doSomething() {
print("Originator: I'm doing something important.")
state = generateRandomString()
print("Originator: and my state has changed to: (state)")
}
private func generateRandomString() -> String {
return String(UUID().uuidString.suffix(4))
}
func save() -> Memento {
return ConcreteMemento(state: state)
}
func restore(memento: Memento) {
guard let memento = memento as? ConcreteMemento else { return }
self.state = memento.state
print("Originator: My state has changed to: (state)")
}
}
Implementation
protocol Memento {
var name: String { get }
var date: Date { get }
}
class ConcreteMemento: Memento {
private(set) var state: String
private(set) var date: Date
init(state: String) {
self.state = state
self.date = Date()
}
var name:String { return state + " " + date.description.suffix(14).prefix(8) }
}
Implementation
class Caretaker {
private lazy var mementos = [Memento]()
private var originator: Originator
init(originator: Originator) {
self.originator = originator
}
func backup() {
print("nSaving Originator's state...n")
mementos.append(originator.save())
}
func undo() {
guard !mementos.isEmpty else { return }
let removedMemento = mementos.removeLast()
print("Restoring state to: " + removedMemento.name)
originator.restore(memento: removedMemento)
}
func showHistory() {
print("Here's the list of mementos:n")
mementos.forEach({ print($0.name) })
}
}
Implementation
let originator = Originator(state: "Super-duper-super-puper-super.")
// Originator: My initial state is: Super-duper-super-puper-super.
let caretaker = Caretaker(originator: originator)
caretaker.backup()
// Saving Originator's state...
originator.doSomething()
// Originator: I'm doing something important.
// Originator: and my state has changed to: B147
caretaker.backup()
// Saving Originator's state...
originator.doSomething()
// Originator: I'm doing something important.
// Originator: and my state has changed to: 20B2
caretaker.backup()
// Saving Originator's state...
Implementation
caretaker.showHistory()
// Super-duper-super-puper-super. 08:22:02
// B147 08:22:02
// 20B2 08:22:02
caretaker.undo()
// Restoring state to: 20B2 08:22:31
// Originator: My state has changed to: 20B2
caretaker.undo()
// Restoring state to: B147 08:22:31
// Originator: My state has changed to: B147
caretaker.undo()
// Caretaker: Restoring state to: Super-duper-super-puper-super. 08:22:31
// Originator: My state has changed to: Super-duper-super-puper-super.
References
[1] Memento in Swift : https://refactoring.guru/design-
patterns/memento/swift/example
[2] 메멘토 패턴 (Memento Pattern in Swift) : https://
jerome.kr/entry/memento-pattern
[3] Design Patterns in Swift #2: Observer and Memento :
https://www.appcoda.com/design-pattern-behavorial/
[4] A Design Pattern Story in Swift – Chapter 17: Memento
: http://audreyli.me/2015/07/15/a-design-pattern-story-in-
swift-chapter-17-memento/
[5] How to Use the Memento Pattern : https://
aruniphoneapplication.blogspot.com/2016/12/the-memento-
pattern.html
References
[6] [Design Pattern] 메멘토(Memento) 패턴 - 디자인 패턴 :
https://palpit.tistory.com/205
[7] Design Patterns - Memento Pattern : https://
www.tutorialspoint.com/design_pattern/
memento_pattern.htm
[8] Design Pattern: Memento Pattern : https://viblo.asia/
p/design-pattern-memento-pattern-eW65GDPOKDO
[9] 메멘토 패턴 : https://ko.wikipedia.org/wiki/메멘토_패턴
[10] Memento Design Pattern : https://
sourcemaking.com/design_patterns/memento
Thank you!

More Related Content

What's hot

DeprecatedAPI로 알아보는 SwiftUI
DeprecatedAPI로 알아보는 SwiftUIDeprecatedAPI로 알아보는 SwiftUI
DeprecatedAPI로 알아보는 SwiftUIBongwon Lee
 
Mulberry: A Mobile App Development Toolkit
Mulberry: A Mobile App Development ToolkitMulberry: A Mobile App Development Toolkit
Mulberry: A Mobile App Development ToolkitRebecca Murphey
 
A New Baseline for Front-End Devs
A New Baseline for Front-End DevsA New Baseline for Front-End Devs
A New Baseline for Front-End DevsRebecca Murphey
 
Leveraging jQuery's Special Events API (JSConf 2012)
Leveraging jQuery's Special Events API (JSConf 2012)Leveraging jQuery's Special Events API (JSConf 2012)
Leveraging jQuery's Special Events API (JSConf 2012)James Greene
 
Desarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móvilesDesarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móvilesLuis Curo Salvatierra
 
Symfony CoP: Form component
Symfony CoP: Form componentSymfony CoP: Form component
Symfony CoP: Form componentSamuel ROZE
 
How I started to love design patterns
How I started to love design patternsHow I started to love design patterns
How I started to love design patternsSamuel ROZE
 
WordPress for developers - phpday 2011
WordPress for developers -  phpday 2011WordPress for developers -  phpday 2011
WordPress for developers - phpday 2011Maurizio Pelizzone
 
jQuery Anti-Patterns for Performance & Compression
jQuery Anti-Patterns for Performance & CompressionjQuery Anti-Patterns for Performance & Compression
jQuery Anti-Patterns for Performance & CompressionPaul Irish
 

What's hot (13)

DeprecatedAPI로 알아보는 SwiftUI
DeprecatedAPI로 알아보는 SwiftUIDeprecatedAPI로 알아보는 SwiftUI
DeprecatedAPI로 알아보는 SwiftUI
 
Mulberry: A Mobile App Development Toolkit
Mulberry: A Mobile App Development ToolkitMulberry: A Mobile App Development Toolkit
Mulberry: A Mobile App Development Toolkit
 
Banquet 47
Banquet 47Banquet 47
Banquet 47
 
A New Baseline for Front-End Devs
A New Baseline for Front-End DevsA New Baseline for Front-End Devs
A New Baseline for Front-End Devs
 
Leveraging jQuery's Special Events API (JSConf 2012)
Leveraging jQuery's Special Events API (JSConf 2012)Leveraging jQuery's Special Events API (JSConf 2012)
Leveraging jQuery's Special Events API (JSConf 2012)
 
Everyday's JS
Everyday's JSEveryday's JS
Everyday's JS
 
Grails UI Primer
Grails UI PrimerGrails UI Primer
Grails UI Primer
 
Email Program By Marcelo
Email Program By MarceloEmail Program By Marcelo
Email Program By Marcelo
 
Desarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móvilesDesarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móviles
 
Symfony CoP: Form component
Symfony CoP: Form componentSymfony CoP: Form component
Symfony CoP: Form component
 
How I started to love design patterns
How I started to love design patternsHow I started to love design patterns
How I started to love design patterns
 
WordPress for developers - phpday 2011
WordPress for developers -  phpday 2011WordPress for developers -  phpday 2011
WordPress for developers - phpday 2011
 
jQuery Anti-Patterns for Performance & Compression
jQuery Anti-Patterns for Performance & CompressionjQuery Anti-Patterns for Performance & Compression
jQuery Anti-Patterns for Performance & Compression
 

More from Bill Kim

[Algorithm] Sorting Comparison
[Algorithm] Sorting Comparison[Algorithm] Sorting Comparison
[Algorithm] Sorting ComparisonBill Kim
 
[Algorithm] Big O Notation
[Algorithm] Big O Notation[Algorithm] Big O Notation
[Algorithm] Big O NotationBill Kim
 
[Algorithm] Shell Sort
[Algorithm] Shell Sort[Algorithm] Shell Sort
[Algorithm] Shell SortBill Kim
 
[Algorithm] Radix Sort
[Algorithm] Radix Sort[Algorithm] Radix Sort
[Algorithm] Radix SortBill Kim
 
[Algorithm] Quick Sort
[Algorithm] Quick Sort[Algorithm] Quick Sort
[Algorithm] Quick SortBill Kim
 
[Algorithm] Heap Sort
[Algorithm] Heap Sort[Algorithm] Heap Sort
[Algorithm] Heap SortBill Kim
 
[Algorithm] Counting Sort
[Algorithm] Counting Sort[Algorithm] Counting Sort
[Algorithm] Counting SortBill Kim
 
[Algorithm] Selection Sort
[Algorithm] Selection Sort[Algorithm] Selection Sort
[Algorithm] Selection SortBill Kim
 
[Algorithm] Merge Sort
[Algorithm] Merge Sort[Algorithm] Merge Sort
[Algorithm] Merge SortBill Kim
 
[Algorithm] Insertion Sort
[Algorithm] Insertion Sort[Algorithm] Insertion Sort
[Algorithm] Insertion SortBill Kim
 
[Algorithm] Bubble Sort
[Algorithm] Bubble Sort[Algorithm] Bubble Sort
[Algorithm] Bubble SortBill Kim
 
[Algorithm] Binary Search
[Algorithm] Binary Search[Algorithm] Binary Search
[Algorithm] Binary SearchBill Kim
 
[Algorithm] Recursive(재귀)
[Algorithm] Recursive(재귀)[Algorithm] Recursive(재귀)
[Algorithm] Recursive(재귀)Bill Kim
 
[Swift] Data Structure - AVL
[Swift] Data Structure - AVL[Swift] Data Structure - AVL
[Swift] Data Structure - AVLBill Kim
 
[Swift] Data Structure - Binary Search Tree
[Swift] Data Structure - Binary Search Tree[Swift] Data Structure - Binary Search Tree
[Swift] Data Structure - Binary Search TreeBill Kim
 
[Swift] Data Structure - Graph(BFS)
[Swift] Data Structure - Graph(BFS)[Swift] Data Structure - Graph(BFS)
[Swift] Data Structure - Graph(BFS)Bill Kim
 
[Swift] Data Structure - Graph(DFS)
[Swift] Data Structure - Graph(DFS)[Swift] Data Structure - Graph(DFS)
[Swift] Data Structure - Graph(DFS)Bill Kim
 
[Swift] Data Structure - Binary Tree
[Swift] Data Structure - Binary Tree[Swift] Data Structure - Binary Tree
[Swift] Data Structure - Binary TreeBill Kim
 
[Swift] Data Structure - Tree
[Swift] Data Structure - Tree[Swift] Data Structure - Tree
[Swift] Data Structure - TreeBill Kim
 
[Swift] Data Structure - Graph
[Swift] Data Structure - Graph[Swift] Data Structure - Graph
[Swift] Data Structure - GraphBill Kim
 

More from Bill Kim (20)

[Algorithm] Sorting Comparison
[Algorithm] Sorting Comparison[Algorithm] Sorting Comparison
[Algorithm] Sorting Comparison
 
[Algorithm] Big O Notation
[Algorithm] Big O Notation[Algorithm] Big O Notation
[Algorithm] Big O Notation
 
[Algorithm] Shell Sort
[Algorithm] Shell Sort[Algorithm] Shell Sort
[Algorithm] Shell Sort
 
[Algorithm] Radix Sort
[Algorithm] Radix Sort[Algorithm] Radix Sort
[Algorithm] Radix Sort
 
[Algorithm] Quick Sort
[Algorithm] Quick Sort[Algorithm] Quick Sort
[Algorithm] Quick Sort
 
[Algorithm] Heap Sort
[Algorithm] Heap Sort[Algorithm] Heap Sort
[Algorithm] Heap Sort
 
[Algorithm] Counting Sort
[Algorithm] Counting Sort[Algorithm] Counting Sort
[Algorithm] Counting Sort
 
[Algorithm] Selection Sort
[Algorithm] Selection Sort[Algorithm] Selection Sort
[Algorithm] Selection Sort
 
[Algorithm] Merge Sort
[Algorithm] Merge Sort[Algorithm] Merge Sort
[Algorithm] Merge Sort
 
[Algorithm] Insertion Sort
[Algorithm] Insertion Sort[Algorithm] Insertion Sort
[Algorithm] Insertion Sort
 
[Algorithm] Bubble Sort
[Algorithm] Bubble Sort[Algorithm] Bubble Sort
[Algorithm] Bubble Sort
 
[Algorithm] Binary Search
[Algorithm] Binary Search[Algorithm] Binary Search
[Algorithm] Binary Search
 
[Algorithm] Recursive(재귀)
[Algorithm] Recursive(재귀)[Algorithm] Recursive(재귀)
[Algorithm] Recursive(재귀)
 
[Swift] Data Structure - AVL
[Swift] Data Structure - AVL[Swift] Data Structure - AVL
[Swift] Data Structure - AVL
 
[Swift] Data Structure - Binary Search Tree
[Swift] Data Structure - Binary Search Tree[Swift] Data Structure - Binary Search Tree
[Swift] Data Structure - Binary Search Tree
 
[Swift] Data Structure - Graph(BFS)
[Swift] Data Structure - Graph(BFS)[Swift] Data Structure - Graph(BFS)
[Swift] Data Structure - Graph(BFS)
 
[Swift] Data Structure - Graph(DFS)
[Swift] Data Structure - Graph(DFS)[Swift] Data Structure - Graph(DFS)
[Swift] Data Structure - Graph(DFS)
 
[Swift] Data Structure - Binary Tree
[Swift] Data Structure - Binary Tree[Swift] Data Structure - Binary Tree
[Swift] Data Structure - Binary Tree
 
[Swift] Data Structure - Tree
[Swift] Data Structure - Tree[Swift] Data Structure - Tree
[Swift] Data Structure - Tree
 
[Swift] Data Structure - Graph
[Swift] Data Structure - Graph[Swift] Data Structure - Graph
[Swift] Data Structure - Graph
 

Recently uploaded

Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 

Recently uploaded (20)

Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 

[Swift] Memento

  • 3. Memento Memento(메멘토) 패턴은 객체의 상태를 저장하고 복원할 수 있는 행동 디자인 패턴입니다. 기본 오리지날 객체는 본래의 기능에만 충실하고 상태 정보에 대한 관리를 메멘토 객체에게 전담하여 상태를 저장하고 복원할 수 있게 한다.
  • 4. Structure Memento 패턴을 UML로 도식화하면 아래와 같습니다.
  • 5. Structure Originator : 상태값을 가지고 있고 객체의 본연의 기능만을 수행 하며 저장 및 복원에 대한 작업은 Memento 객체에게 넘기는 객체 Memento : Originator 객체의 스냅샷 역할을 하는 값 객체이다. 메멘토 데이터는 생성장를 통해서 한번만 전달하는 것이 일반적입 니다. ConcreteMemento : Memento 객체를 상속받아 메멘토 객체가 가진 데이터에 대한 초기화를 진행하는 클래스 객체 Caretaker(Client) : Originator 객체에 대한 상태가 언제 바뀌 고 저장되었는지를 알고 있는 객체, 또한 스냅샷 리스트를 가지고 있 고 복원을 할 경우 가장 최상위의 Originator 상태로 복원을 진행 하는 객체
  • 6. Implementation 구체적인 구현에 대해서 소스 코드를 통하여 살펴봅니다. class Originator { private var state: String init(state: String) { self.state = state print("Originator: My initial state is: (state)") } func doSomething() { print("Originator: I'm doing something important.") state = generateRandomString() print("Originator: and my state has changed to: (state)") } private func generateRandomString() -> String { return String(UUID().uuidString.suffix(4)) } func save() -> Memento { return ConcreteMemento(state: state) } func restore(memento: Memento) { guard let memento = memento as? ConcreteMemento else { return } self.state = memento.state print("Originator: My state has changed to: (state)") } }
  • 7. Implementation protocol Memento { var name: String { get } var date: Date { get } } class ConcreteMemento: Memento { private(set) var state: String private(set) var date: Date init(state: String) { self.state = state self.date = Date() } var name:String { return state + " " + date.description.suffix(14).prefix(8) } }
  • 8. Implementation class Caretaker { private lazy var mementos = [Memento]() private var originator: Originator init(originator: Originator) { self.originator = originator } func backup() { print("nSaving Originator's state...n") mementos.append(originator.save()) } func undo() { guard !mementos.isEmpty else { return } let removedMemento = mementos.removeLast() print("Restoring state to: " + removedMemento.name) originator.restore(memento: removedMemento) } func showHistory() { print("Here's the list of mementos:n") mementos.forEach({ print($0.name) }) } }
  • 9. Implementation let originator = Originator(state: "Super-duper-super-puper-super.") // Originator: My initial state is: Super-duper-super-puper-super. let caretaker = Caretaker(originator: originator) caretaker.backup() // Saving Originator's state... originator.doSomething() // Originator: I'm doing something important. // Originator: and my state has changed to: B147 caretaker.backup() // Saving Originator's state... originator.doSomething() // Originator: I'm doing something important. // Originator: and my state has changed to: 20B2 caretaker.backup() // Saving Originator's state...
  • 10. Implementation caretaker.showHistory() // Super-duper-super-puper-super. 08:22:02 // B147 08:22:02 // 20B2 08:22:02 caretaker.undo() // Restoring state to: 20B2 08:22:31 // Originator: My state has changed to: 20B2 caretaker.undo() // Restoring state to: B147 08:22:31 // Originator: My state has changed to: B147 caretaker.undo() // Caretaker: Restoring state to: Super-duper-super-puper-super. 08:22:31 // Originator: My state has changed to: Super-duper-super-puper-super.
  • 11. References [1] Memento in Swift : https://refactoring.guru/design- patterns/memento/swift/example [2] 메멘토 패턴 (Memento Pattern in Swift) : https:// jerome.kr/entry/memento-pattern [3] Design Patterns in Swift #2: Observer and Memento : https://www.appcoda.com/design-pattern-behavorial/ [4] A Design Pattern Story in Swift – Chapter 17: Memento : http://audreyli.me/2015/07/15/a-design-pattern-story-in- swift-chapter-17-memento/ [5] How to Use the Memento Pattern : https:// aruniphoneapplication.blogspot.com/2016/12/the-memento- pattern.html
  • 12. References [6] [Design Pattern] 메멘토(Memento) 패턴 - 디자인 패턴 : https://palpit.tistory.com/205 [7] Design Patterns - Memento Pattern : https:// www.tutorialspoint.com/design_pattern/ memento_pattern.htm [8] Design Pattern: Memento Pattern : https://viblo.asia/ p/design-pattern-memento-pattern-eW65GDPOKDO [9] 메멘토 패턴 : https://ko.wikipedia.org/wiki/메멘토_패턴 [10] Memento Design Pattern : https:// sourcemaking.com/design_patterns/memento