.NET乐园
一个梦想,一个行动…… (欢迎光临我的淘宝http://pipis.taobao.com,专营户外手电筒、头灯、营地灯、自行车灯)
动机:在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样就可以将该对象恢复到原先保存的状态。

场景:此处以图形系统为例,圆为原发器,该系统对圆进行处理,并保存可恢复状态序列。


结构图

Memento模式结构图


代码

namespace DesignPattern.Memento
{
    
/// <summary>
    
/// 原发器
    
/// </summary>

    public class Round 
    
{
        
private Point centerPoint;
        
private int radius;

        
public Round(Point centerPoint, int radius)
        
{
            
this.centerPoint = centerPoint;
            
this.radius = radius;
        }


        
public RoundMemento CreateMemento()
        
{
            RoundMemento memento 
= new RoundMemento();
            memento.SetState(
this.centerPoint, this.radius);
            
return memento;
        }


        
public void SetMemento(RoundMemento memento)
        
{
            
this.centerPoint = memento.centerPoint;
            
this.radius = memento.radius;
        }


        
public void Move(Point point)
        
{
        }


        
public void SetLength(int radius)
        
{
        }

    }


    
/// <summary>
    
/// 备忘录
    
/// </summary>

    public class RoundMemento
    
{
        
internal Point centerPoint;
        
internal int radius;

        
public RoundMemento()
        
{
        }


        
internal void SetState(Point centerPoint, int radius)
        
{
            
this.centerPoint = centerPoint;
            
this.radius = radius;
        }

    }

}

namespace DesignPattern.Memento
{
    
public class GraphicsSystem
    
{
        Round round 
= new Round (new Point(), 10);
        IList
<RoundMemento> mementos;

        
public GraphicsSystem()
        
{
            mementos 
= new List<RoundMemento>();
        }


        
public void Process()
        
{
            mementos.Add(round.CreateMemento());
            
// 操作圆
        }


        
public void Undo(int index)
        
{
            round.SetMemento(mementos[index]);
        }

    }

}


要点
        1、备忘录(Memento)存储原发器(Originator)对象的内部状态,在需要时恢复原发器状态。本模式适用于“由原发器管理,却又必须存储在原发器之外的信息”。
        2、实现本模式时,要防止原发器以外的对象访问备忘录对象。备忘录对象有两个接口,一个为原发器使用的宽接口,一个为其他对象使用的窄接口。
        3、实现本模式时,要考虑拷贝对象状态的效率问题,如果对象开销比较大,可以采用某种增量式改变来改进本模式。
posted on 2007-08-13 23:26  Charly  阅读(1470)  评论(0编辑  收藏  举报