Net设计模式实例之备忘录模式(Memento Pattern)(2)

四.实例分析(Example

1、场景

首先定义销售代理 Noel van H alen 的相关信息 . 然后保存到备忘录中 , 而定义销售代理 Leo Welch 相关信息。然后又回覆前一代理 Noel van H alen 的信息。。结构 如下图所示
Net设计模式实例之备忘录模式(Memento Pattern)(2)_第1张图片
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 Main (string [] args)
{
    SalesProspect s = new SalesProspect ();
    s.Name = "Noel van H alen " ;
    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、实例运行结果

五、总结(Summary

本文对备忘录模式设计思想、结构和结构代码进行了分析,并以一实例进一步阐述了备忘录模式的 C# 实现。

你可能感兴趣的:(备忘录模式,C#设计模式,Net设计模式,Memento_Pattern,备忘录模式实例)