DesignPatterns
1. 關於 Memento
2. UML
3. 將 UML 轉為程式碼
4. 情境
OS:Windows 10
IDE:Visual Studio 2019
Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later.
by Gang of Four
Memento(備忘錄)屬於行為型(Behavioral Patterns),當遇到需要狀態回到某個狀態時,可藉由 Memento 來將物件備份,包含物件中 private 的屬性都可以透過 Memento 來記錄,也可以將每次異動物件都記錄至 Memento 來達到上一步、下一步的功能。
優點:
缺點:
Class 間關聯:
Class:
內部狀態需要保存的物件
負責保存 Originator 的狀態
存放 Memento 但不操作
originator
並給定初始值 Oncaretaker
並透過originator
建立Memento
State
的值Memento
還原State
的值執行結果
我們接到了一個門市結帳刷條碼要能夠「上一步」的需求
結帳刷條碼
使用Stack<string>
保存每次刷條碼新增商品的快照
存放 Memento 但不操作
scanTheBarcode
caretaker
並透過scanTheBarcode
建立Memento
PreviousStep
移除前一項商品執行結果
GitHub:Behavioral_06_Memento