泡泡

              宠辱不惊-闲看庭前花开花落
                           去留无意-漫观天外云展云舒
  首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

18)Memento

Posted on 2007-09-21 15:12  AlanPaoPao  阅读(162)  评论(0)    收藏  举报
    备忘录模式的目的是: 为一个对象提供状态储存和状态恢复的手段
    实例代码:
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; }
  }

}

class ProspectMemory
{
  
private Memento memento;
  
public Memento Memento
  
{
    
set { memento = value; }
    
get return memento; }
  }

}

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;
  }

}

class MainApp
{
  
static void Main()
  
{
    SalesProspect s 
= new SalesProspect();
    s.Name 
= "Noel van Halen";
    s.Phone 
= "(412) 256-0990";
    s.Budget 
= 25000.0;
    ProspectMemory m 
= new ProspectMemory();
    m.Memento 
= s.SaveMemento();
    s.Name 
= "Leo Welch";
    s.Phone 
= "(310) 209-7111";
    s.Budget 
= 1000000.0;
    s.RestoreMemento(m.Memento);
    Console.Read();
  }

}