B/O - Memento
- Category: behavioral
- Type: object
- Motivation: memento is capture and storing the current state of an object in a manner that it can be restored later on in a smooth manner
// caretaker
do {
var history: [Memento] = []
let editor = Editor()
editor.type("foo")
history.append(editor.save())
print(editor.content)
editor.type("bar")
print(editor.content)
editor.restore(history[0])
print(editor.content)
}
// memento
struct Memento
{
let content: String
}
// originator
class Editor
{
var content: String = ""
func type(_ words: String)
{
content += words
}
func save() -> Memento
{
return Memento(content: content)
}
func restore(_ memento: Memento)
{
content = memento.content
}
}