天天看點

C#設計模式之:備忘錄模式

備忘錄模式(Memento)

在不破壞封裝性的前提下,捕獲一個對象的内部狀态,并在該對象之外儲存這個狀态。這樣以後就可将該對象恢複到原先儲存的狀态

UML

C#設計模式之:備忘錄模式

代碼

class Memento
{
    private string state;

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

    public string State
    {
        get { return      
class Caretaker
{
    private Memento memento;

    internal Memento Memento { get => memento; set => memento = value; }
}      
class Originator
{
    private string state;
    public string State { get => state; set => state = value; }

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

    public void SetMemento(Memento memento)
    {
        state = memento.State;
    }

    public void Show()
    {
        Console.WriteLine("State = "      
// test
Originator o = new Originator();
o.State = "On";
o.Show();

Caretaker c = new Caretaker();
c.Memento = o.CreateMemento();

o.State = "Off";
o.Show();

o.SetMemento(c.Memento);
o.Show();      
// result
State = On
State = Off
State = On      

說明

缺陷