Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Applied Java™ Patterns - Stephen Stelting, Olav Maassen.pdf
Скачиваний:
202
Добавлен:
24.05.2014
Размер:
2.84 Mб
Скачать

A better approach is to use an object to contain the data to be stored. You would send this object that could be used to recreate the original, instead of sending raw data. Other objects would not be able to read or modify the data, since the data to be stored would be encapsulated.

This is the Memento pattern, where an object is used as a “souvenir” that only has value to the original holder and helps it remember a previous state.

Applicability

Use Memento when all of the following apply:

A snapshot of the state of an object should be taken.

That snapshot is used to recreate the original state.

A direct interface to the object to read its internal state would violate its encapsulation, because this would also reveal the internal workings.

Description

If you have implemented encapsulation correctly, all objects have private states, and will allow access to the attributes only through methods. But it might be necessary to pass the current state to another object: for instance, when the object’s state must be restorable at a later point in time (undo).

One way to do this is by handing the state directly to the interested party. This has the potential for some huge drawbacks:

It exposes the internal structure of your object.

It enables the other object to arbitrarily change the state of your object.

The solution is to wrap the state that you wish to preserve in an object, using Memento. A Memento is an object that contains the current internal state of the Originator object. Only the Originator can store and retrieve information from the Memento. To the outside world the Memento is just an arbitrary object.

The Memento pattern is like a credit card. Although you don’t know what is actually really on the card, you know what it provides (lots of buying power to buy lots of toys). In the Memento’s case, it allows you to preserve and restore the state.

Implementation

The Memento class diagram is shown in Figure 2.9.

Figure 2.9. Memento class diagram

Implementing the Memento requires:

Originator – Creates Memento and uses this Memento to later restore its state.

Memento – Static inner class of the Originator and holder of the Originator’s state. The Originator determines how much is stored in the Memento and only the Originator should be able to read the Memento.

64