Memento Pattern Tutorial

This tutorial is aimed to guide the definition and application of Gang of Four (GoF) memento design pattern. By reading this tutorial, you will know how to develop a model for the memento pattern, and how to apply it in practice.

October 21, 2009
Views: 41,327
PDF Download

Modeling a Design Pattern with a Class Diagram

  1. Create a new project named Design Patterns.
  2. Create a class diagram named Memento.
    new diagram
  3. Select Class from the diagram toolbar. Click on the diagram to create a class. Name it Originator.
    create colleague
  4. Right-click on the Originator class and select Add > Operation from the popup menu.
    add oper to originator
  5. Name the operation SetMemento(m : Memento).
  6. Repeat steps 4 and 5 to create the operation CreateMemento() : Memento.
    oper added to originator
  7. Right-click on the Originator class and select Add > Attribute from the popup menu.
    add attr
  8. Name the attribute state.
    state added
  9. Move the mouse cursor over the Originator class and drag out Dependency > Class to create a dependent class Memento.
  10. Create two operations in class Memento: GetState() and SetState().
  11. Create attribute state in class Memento.
    oper added to memento
  12. Create a class Caretaker near class Memento.
    caretaker
  13. Move the mouse cursor over the Caretaker class and drag out Aggregation > Class to connect to Memento.
    caretaker connect to memento

Defining a Pattern

  1. Select all classes on the class diagram.
    select all classes
  2. Right-click on the selection and select Define Design Pattern... from the popup menu.
    define pattern
  3. In the Define Design Pattern dialog box, specify the pattern name Memento. Keep the file name as is. Click OK to proceed.
    name pattern

Applying a Design Pattern on a Class Diagram

In this section, we will try to make use of the memento pattern to model a part of a sales ordering system, with regards to the state of a sales order.

  1. Create a new project Order Processing System.
  2. Create a class diagram Domain Model.
  3. Right-click on the class diagram and select Utilities > Apply Design Pattern... from the popup menu.
    apply design pattern
  4. In the Design Pattern dialog box, select Memento from the list of patterns.
    select memento
  5. At the bottom of the pane, rename Originator and Caretaker to Order and Transaction.
    rename classes
  6. Click OK to confirm editing and apply the pattern to the diagram.
  7. Tidy up the diagram. It should become:
    result