Memento

From CDOT Wiki
Revision as of 17:21, 13 April 2007 by Ajhooper (talk | contribs)
Jump to: navigation, search


Description

The Memento design pattern is used to store the state of an object so that it can later be restored to that state. In the diagram below the Originator object is creates a Memento that will store it's internal state and can later retrieve that state. The Caretaker makes sure that only the object that creates the memento will be able to access it to restore it's state. Although if can have other uses, this pattern is often used for undo/redo operations in many different programs.

Diagram

MementoDiagram.jpg

Examples

This is a simple example of a memento in C#:

// Memento pattern -- Structural example

using System;

namespace DoFactory.GangOfFour.Memento.Structural
{

  // MainApp test application

  class MainApp
  {
    static void Main()
    {
      Originator o = new Originator();
      o.State = "On";

      // Store internal state
      Caretaker c = new Caretaker();
      c.Memento = o.CreateMemento();

      // Continue changing originator
      o.State = "Off";

      // Restore saved state
      o.SetMemento(c.Memento);

      // Wait for user
      Console.Read();
    }
  }

  // "Originator"

  class Originator
  {
    private string state;

    // Property
    public string State
    {
      get{ return state; }
      set
      {
        state = value;
        Console.WriteLine("State = " + state);
      }
    }

    public Memento CreateMemento()
    {
      return (new Memento(state));
    }

    public void SetMemento(Memento memento)
    {
      Console.WriteLine("Restoring state:");
      State = memento.State;
    }
  }

  // "Memento"

  class Memento
  {
    private string state;

    // Constructor
    public Memento(string state)
    {
      this.state = state;
    }

    // Property
    public string State
    {
      get{ return state; }
    }
  }

  // "Caretaker"

  class Caretaker
  {
    private Memento memento;

    // Property
    public Memento Memento
    {
      set{ memento = value; }
      get{ return memento; }
    }
  }
}

//Output
//State = On
//State = Off
//Restoring state:
//State = On