Net設計模式例項之備忘錄模式(Memento Pattern)(2)

weixin_34219944發表於2010-01-25

四.例項分析(Example

1、場景

首先定義銷售代理Noel van H<?XML:NAMESPACE PREFIX = ST1 />alen的相關資訊.然後儲存到備忘錄中,而定義銷售代理Leo Welch相關資訊。然後又回覆前一代理Noel van Halen的資訊。。結構如下圖所示<?XML:NAMESPACE PREFIX = O />

SalesProspect:發起人

SaveMemento方法:建立備忘錄

RestoreMemento方法:回覆備忘錄

Memento:備忘錄,需要備份的資訊有姓名、電話和預算

ProspectMemory:負責儲存備忘錄Memento

2、程式碼

1、發起人類SalesProspect

class SalesProspect

{

    private string _name;

    private string _phone;

    private double _budget;

    public string Name

    {

        get { return _name; }

        set

        {

            _name = value;

            Console.WriteLine("Name:  " + _name);

        }

    }

    public string Phone

    {

        get { return _phone; }

        set

        {

            _phone = value;

            Console.WriteLine("Phone: " + _phone);

        }

    }

    public double Budget

    {

        get { return _budget; }

        set

        {

            _budget = value;

            Console.WriteLine("Budget: " + _budget);

        }

    }

    public Memento SaveMemento()

    {

        Console.WriteLine("\nSaving state --\n");

        return new Memento(_name, _phone, _budget);

    }

    public void RestoreMemento(Memento memento)

    {

        Console.WriteLine("\nRestoring state --\n");

        this.Name = memento.Name;

        this.Phone = memento.Phone;

        this.Budget = memento.Budget;

    }

}

 

2、備忘錄類Memento

class Memento

{

    private string _name;

    private string _phone;

    private double _budget;

    public Memento(string name, string phone, double budget)

    {

        this._name = name;

        this._phone = phone;

        this._budget = budget;

    }

    public string Name

    {

        get { return _name; }

        set { _name = value; }

    }

    public string Phone

    {

        get { return _phone; }

        set { _phone = value; }

    }

    public double Budget

    {

        get { return _budget; }

        set { _budget = value; }

    }

}

 

3、管理者類ProspectMemory

class ProspectMemory

{

    private Memento _memento;

    // Property

    public Memento Memento

    {

        set { _memento = value; }

        get { return _memento; }

    }

}

 

3、客戶端程式碼

static void <?XML:NAMESPACE PREFIX = ST2 />Main(string[] args)

{

    SalesProspect s = new SalesProspect();

    s.Name = "Noel van Halen";

    s.Phone = "(412) 256-0990";

    s.Budget = 25000.0;

    // Store internal state

    ProspectMemory m = new ProspectMemory();

    m.Memento = s.SaveMemento();

 

    // Continue changing originator

    s.Name = "Leo Welch";

    s.Phone = "(310) 209-7111";

    s.Budget = 1000000.0;

    // Restore saved state

    s.RestoreMemento(m.Memento);

    Console.ReadKey();

}

3、例項執行結果

<?XML:NAMESPACE PREFIX = V />

五、總結(Summary

本文對備忘錄模式設計思想、結構和結構程式碼進行了分析,並以一例項進一步闡述了備忘錄模式的C#實現。

相關文章