Design Pattern: Memento Pattern

Tram Ho

I. Introduction:

Memento is a Design Pattern of the Behavior type. It allows us to store and restore the status of an object that does not reveal its inner details. Memento Pattern consists of the following components:

  • Originator : An object whose state is stored or restored.
  • Mementor: the state (State) of the object when being stored.
  • Caretaker: role storage and allocation of Memento. It is responsible for storing States in Memento form and allocating States to Objects as needed.

II. How it works:

Memento Pattern will structure the data to save an Object into a State , then will save this State . The State after being saved will be called the Memento . CareTaker will take the role of storing the State into Memento and export Mementos into State for use. Because the state of objects is stored in the state , when the state is passed through different objects, it will not reveal detailed implementations of those objects.

III. When is Memento Pattern used?

Memento Pattern is used whenever we want to save and then restore the state of an Object. For example, when we play a game, we want to save all the state we played before so that after quitting the game and reopening we can continue playing, then we can apply Memento Pattern to solve this problem.

IV. For example:

In the example, we will use the class Game with the role of Originator . Inside the class Game will contain a State to save its state. The Game ‘s state will be saved in the UserDefault , so we need to adopt the Codable protocol.

The Game Object will be saved to the UserDefault as a Data . Therefore, Data in Swift in this example will act as Memento.

To manage the storage of Mementos, we will need CareTaker. GameSystem acts as CareTaker. This class will be responsible for storing or retrieving Mementos when necessary.


V. References:

Share the news now

Source : Viblo