简体   繁体   中英

What is the difference between the Momento and Prototype Design Pattern?

Observed differences between the Momento and Prototype Design Pattern (from the GOF):

  1. The Momento design pattern uses class x to create a snapshot of the internal state of class y. The Prototype design pattern uses class y to create a snapshot (=clone) of the internal state of class y.
  2. The Momento design pattern is a behavioral pattern and the Prototype design pattern is a creational design pattern.
  3. The Momento design pattern makes it possible to create a partial snapshot of the state of class y in class x. In the Prototype Design pattern a full snapshot (=clone) of class y is created.
  4. Different in intent.

The same result can be achieved with both the Momento and Prototype Design Pattern:

  • Prototype design pattern: the state of object x can be cloned, stored in a list, and assigned to object x in case an undo operation is required.
  • Momento design pattern: the state of object x can be saved inside object y, stored in a list, and assigned to object x in case an undo operation is required.

What is the difference between the two patterns (besides the ones already listed)? When would we use one over the other? The Prototype pattern seems to me the preferred option, in case the full object needs to be 'snapshotted' and stacked in a list for an undo operation.

The Prototype pattern describes a way in which objects are created. How the objects behave is irrelevant to the Prototype pattern. The Memento pattern describes a way in which objects behave. How the objects are created is irrelevant to the Memento pattern.

To state this more broadly, any creational pattern could produce the objects necessary for any behavioral (or structural or any other) pattern. This does not imply the creational patterns overlap in any way with whatever pattern(s) happen to be implemented by the objects they create.

The essence of a Memento is an object with two interfaces. From the GoF book page 285,

Mementos have effectively two interfaces. Caretaker sees a narrow interface to the Memento—it can only pass the memento to other objects. Originator, in contrast, sees a wide interface, one that lets it access all the data...

So the key to the Memento pattern is in implementing these two interfaces in one object. If you choose to instantiate that object via cloning, you can employ two patterns; but there is a clear boundary between creation and behavior. The Prototype pattern stops once a clone is created. The Memento pattern starts when an object utilizes both a narrow and a wide interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM