• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
gooliugle
博客园    首页    新随笔    联系   管理    订阅  订阅
大话设计模式读书笔记14----备忘录(Memento)

备忘录(Memento):在不破坏封装的前提下,捕获一个对象的内部状态,并在该对象外保存这个状态。这样就可将该对象恢复到原先保存的状态。

1、Originator(发起人):负责创建一个Memento备忘录,用以记录当前时刻它的内部状态,并可使用备忘录恢复内部状态。Originator可根据需要决定Memento存储 Originator的哪些内部状态。

2、 Memento(备忘录):负责存储Originator内部状态,并可防止Originator以外的对象访问备忘录Memento。备忘录有两个接口,Caretaker只能看到备忘录的窄接口,它只能将备忘录传递给其他对象。Originator能看到一个粗接口,允许它访问返回到先前状态的所有数据。

备忘录模式代码
using System;
using System.Collections.Generic;
using System.Text;

namespace Memento
{
    
class Program
    {
        
static void Main(string[] args)
        {
            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();
            Console.ReadLine();
        }
    }
    
class Originator
    {
        
private string _state;

        
public string State
        {
            
get { return _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="+State);
        }
    }
    
class Memento
    {
        
private string _state;

        
public string State
        {
            
get { return _state; }
            
set { _state = value; }
        }
        
public Memento(string state)
        {
            
this._state = state;
        }
 
    }
    
class Caretaker
    {
        
private Memento memento;

        
internal Memento Memento
        {
            
get { return memento; }
            
set { memento = value; }
        }
 
    }
}


 

 

 

posted on 2010-04-29 20:08  gooliugle  阅读(348)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3