creativity in code.

creativity is that spark of electricity before an explosion.
it allows us, in a single instance to explore all possibilities without hesitation.

Programming - Memento Behavioral Design Pattern


Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later.


The classes and/or objects participating in this pattern are:


  • Memento
    • stores internal state of the Originator object. The memento may store as much or as little of the originator's internal state as necessary at its originator's discretion.
    • protect against access by objects of other than the originator. Mementos have effectively two interfaces. Caretaker sees a narrow interface to the Memento -- it can only pass the memento to the other objects. Originator, in contrast, sees a wide interface, one that lets it access all the data necessary to restore itself to its previous state. Ideally, only the originator that produces the memento would be permitted to access the memento's internal state.
  • Originator
    and
    • creates a memento containing a snapshot of its current internal state.
    • uses the memento to restore its internal state
  • Caretaker
    • is responsible for the memento's safekeeping
    • never operates on or examines the contents of a memento.
// 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; }
}
}
}
and
Output expected:
State = On
State = Off
Restoring state:
State = On



Other pages of interest:
[+] Programming - Java - Conditional Operators
[+] Object Oriented Programming


Comments(0)

add comment Add Comment

Add your comment

Email address:
Your name:
Do you want your email to be visible?: