
using System;
using System.Collections.Generic;
using System.Text;
///Memento(备忘录)模式 在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样以后就可将该对象恢复到原先保存的状态。
///add by jzh 2007-04-29
namespace DesignPattern
{
/// <summary>
/// Originator(原生者),就是需要被保存状态以便恢复的那个对象
/// </summary>
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;
}
}
///// <summary>
///// 一个Memento对象,这个对象主要是保存原生者的状态,
///// 并在适当的时间恢复到原生者里去。
///// 而这个适当的时间就是由CareTaker(管理者)来决定的。
///// </summary>
class Memento
{
private string state;
// Constructor
public Memento(string state)
{
this.state = state;
}
// Property
public string State
{
get { return state; }
}
}
/// <summary>
/// CareTaker(管理者)
/// </summary>
class Caretaker
{
private Memento memento;
// Property
public Memento Memento
{
set { memento = value; }
get { return memento; }
}
}
class Client
{
public static void Main()
{
Originator o = new Originator();
o.State = "开启";
// 保存
Caretaker c = new Caretaker();
c.Memento = o.CreateMemento();
// 修改
o.State = "关闭";
//恢复
o.SetMemento(c.Memento);
Console.ReadLine();
}
}
}