Chapter 7: Memento Pattern

大綱

When should you use it?

  • The memento pattern allows an object to be saved and restored.

    • The originator is the object to be saved or restored.

    • The memento represents a stored state.

    • The caretaker requests a save from the originator and receives a memento in response.

      • The caretaker is responsible for persisting the memento and, later on, providing the memento back to the originator to restore the originator’s state.

  • When should you use it?

    • Use the memento pattern whenever you want to save and later restore an object’s state.

Playground example

  • 目標: use this pattern to implement a save game system, where the originator is the game state (such as level, health, number of lives, etc),

    • the memento is saved data

    • the caretaker is the gaming system.

  • Originator

  • Memento

  • CareTaker

What should you be careful about?

  • Be careful when adding or removing Codable properties: both encoding and decoding can throw an error. If you force unwrap these calls using try! and you’re missing any required data, your app will crash!

    • To mitigate this problem, avoid using try! unless you’re absolutely sure the operation will succeed. You should also plan ahead when changing your models.

  • carefully consider how to handle version upgrades.

    • You might choose to delete old data whenever you encounter a new version, create an upgrade path to convert from old to new data, or even use a combination of these approaches.

Tutorial project

Key points

  • The memento pattern allows an object to be saved and restored. It involves three types: the originator, memento and caretaker.

  • The originator is the object to be saved; the memento is a saved state; and the caretaker handles, persists and retrieves mementos.

  • iOS provides Encoder for encoding a memento to, and Decoder for decoding from, a memento. This allows encoding and decoding logic to be used across originators.

Last updated