Memento:
Allows
you to save the state of an object externally from that object.
* Without violating encapsulation, capture and externalize an object's internal state so that the
object can be restored to this state later.
class Program
{
static void Main(string[] args)
{
Originator org = new Originator();
org.State = "ON";
//Store internal state
Caretaker c = new Caretaker();
c.Memento = org.CreateMemento();
//Continue changing originator
org.State = "OFF";
//Restore saved state
org.SetMemento(c.Memento);
Console.ReadKey();
}
}
class Originator
{
private string _state;
public string State
{
get { return _state; }
set
{
_state = value;
Console.WriteLine("State = " + _state);
}
}
//Creates memento
public Memento CreateMemento()
{
return (new Memento(_state));
}
public void SetMemento(Memento memento)
{
Console.WriteLine("Restoring state..");
State = memento.State;
}
}
class Memento
{
private string _state;
public Memento(string state)
{
this._state = state;
}
public string State
{
get { return _state; }
}
}
class Caretaker
{
private Memento _memento;
public Memento Memento
{
set { _memento = value; }
get { return _memento; }
}
}
class Program
{
static void Main(string[] args)
{
Originator org = new Originator();
org.State = "ON";
//Store internal state
Caretaker c = new Caretaker();
c.Memento = org.CreateMemento();
//Continue changing originator
org.State = "OFF";
//Restore saved state
org.SetMemento(c.Memento);
Console.ReadKey();
}
}
class Originator
{
private string _state;
public string State
{
get { return _state; }
set
{
_state = value;
Console.WriteLine("State = " + _state);
}
}
//Creates memento
public Memento CreateMemento()
{
return (new Memento(_state));
}
public void SetMemento(Memento memento)
{
Console.WriteLine("Restoring state..");
State = memento.State;
}
}
class Memento
{
private string _state;
public Memento(string state)
{
this._state = state;
}
public string State
{
get { return _state; }
}
}
class Caretaker
{
private Memento _memento;
public Memento Memento
{
set { _memento = value; }
get { return _memento; }
}
}
No comments:
Post a Comment