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

Mulberry: A Mobile App Development Toolkit
Mulberry: A Mobile App Development ToolkitMulberry: A Mobile App Development Toolkit
Mulberry: A Mobile App Development Toolkit
Rebecca Murphey
 
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
Luis Curo Salvatierra
 
jQuery Anti-Patterns for Performance & Compression
jQuery Anti-Patterns for Performance & CompressionjQuery Anti-Patterns for Performance & Compression
jQuery Anti-Patterns for Performance & Compression
Paul 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

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

The basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptxThe basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptx
heathfieldcps1
 
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
中 央社
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
中 央社
 

Recently uploaded (20)

The Ball Poem- John Berryman_20240518_001617_0000.pptx
The Ball Poem- John Berryman_20240518_001617_0000.pptxThe Ball Poem- John Berryman_20240518_001617_0000.pptx
The Ball Poem- John Berryman_20240518_001617_0000.pptx
 
The basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptxThe basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptx
 
Features of Video Calls in the Discuss Module in Odoo 17
Features of Video Calls in the Discuss Module in Odoo 17Features of Video Calls in the Discuss Module in Odoo 17
Features of Video Calls in the Discuss Module in Odoo 17
 
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjStl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
 
Exploring Gemini AI and Integration with MuleSoft | MuleSoft Mysore Meetup #45
Exploring Gemini AI and Integration with MuleSoft | MuleSoft Mysore Meetup #45Exploring Gemini AI and Integration with MuleSoft | MuleSoft Mysore Meetup #45
Exploring Gemini AI and Integration with MuleSoft | MuleSoft Mysore Meetup #45
 
II BIOSENSOR PRINCIPLE APPLICATIONS AND WORKING II
II BIOSENSOR PRINCIPLE APPLICATIONS AND WORKING IIII BIOSENSOR PRINCIPLE APPLICATIONS AND WORKING II
II BIOSENSOR PRINCIPLE APPLICATIONS AND WORKING II
 
UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024
 
An Overview of the Odoo 17 Discuss App.pptx
An Overview of the Odoo 17 Discuss App.pptxAn Overview of the Odoo 17 Discuss App.pptx
An Overview of the Odoo 17 Discuss App.pptx
 
....................Muslim-Law notes.pdf
....................Muslim-Law notes.pdf....................Muslim-Law notes.pdf
....................Muslim-Law notes.pdf
 
Graduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptxGraduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptx
 
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
 
Operations Management - Book1.p - Dr. Abdulfatah A. Salem
Operations Management - Book1.p  - Dr. Abdulfatah A. SalemOperations Management - Book1.p  - Dr. Abdulfatah A. Salem
Operations Management - Book1.p - Dr. Abdulfatah A. Salem
 
Removal Strategy _ FEFO _ Working with Perishable Products in Odoo 17
Removal Strategy _ FEFO _ Working with Perishable Products in Odoo 17Removal Strategy _ FEFO _ Working with Perishable Products in Odoo 17
Removal Strategy _ FEFO _ Working with Perishable Products in Odoo 17
 
IPL Online Quiz by Pragya; Question Set.
IPL Online Quiz by Pragya; Question Set.IPL Online Quiz by Pragya; Question Set.
IPL Online Quiz by Pragya; Question Set.
 
The Last Leaf, a short story by O. Henry
The Last Leaf, a short story by O. HenryThe Last Leaf, a short story by O. Henry
The Last Leaf, a short story by O. Henry
 
demyelinated disorder: multiple sclerosis.pptx
demyelinated disorder: multiple sclerosis.pptxdemyelinated disorder: multiple sclerosis.pptx
demyelinated disorder: multiple sclerosis.pptx
 
Pragya Champions Chalice 2024 Prelims & Finals Q/A set, General Quiz
Pragya Champions Chalice 2024 Prelims & Finals Q/A set, General QuizPragya Champions Chalice 2024 Prelims & Finals Q/A set, General Quiz
Pragya Champions Chalice 2024 Prelims & Finals Q/A set, General Quiz
 
Mattingly "AI and Prompt Design: LLMs with Text Classification and Open Source"
Mattingly "AI and Prompt Design: LLMs with Text Classification and Open Source"Mattingly "AI and Prompt Design: LLMs with Text Classification and Open Source"
Mattingly "AI and Prompt Design: LLMs with Text Classification and Open Source"
 
Software testing for project report .pdf
Software testing for project report .pdfSoftware testing for project report .pdf
Software testing for project report .pdf
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
 

[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