zoukankan      html  css  js  c++  java
  • 设计模式系列

    备忘录模式通过保存一个对象的某个状态,以便在需要的时候恢复该对象。

    介绍

    备忘录模式属于行为型模式,它通过在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。

    类图描述

    代码实现

    1、创建实体类

    public class Memento
    {
        private string state;
        public Memento(string state)
        {
            this.state = state;
        }
    
        public string GetState() => state;
    }
    

    2、创建状态处理类

    public class Originator
    {
        private string state;
        public void SetState(string state)
        {
            this.state = state;
        }
    
        public string GetState()
        {
            return state;
        }
    
        public Memento SaveStateToMemento()
        {
            return new Memento(this.state);
        }
    
        public void GetStateFromMemento(Memento memento)
        {
            state = memento.GetState();
        }
    }
    

    3、创建储存集合

    public class CareTaker
    {
        private List<Memento> mementoList = new List<Memento>();
    
        public void Add(Memento state)
        {
            mementoList.Add(state);
        }
    
        public Memento Get(int index)
        {
            return mementoList[index];
        }
    }
    

    4、上层调用

    class Program
    {
        static void Main(string[] args)
        {
            Originator originator = new Originator();
            CareTaker careTaker = new CareTaker();
            originator.SetState("State #1");
            originator.SetState("State #2");
            careTaker.Add(originator.SaveStateToMemento());
            originator.SetState("State #3");
            careTaker.Add(originator.SaveStateToMemento());
            originator.SetState("State #4");
    
            Console.WriteLine($"Current State:{originator.GetState()}");
            originator.GetStateFromMemento(careTaker.Get(0));
            Console.WriteLine($"First saved State:{originator.GetState()}");
            originator.GetStateFromMemento(careTaker.Get(1));
            Console.WriteLine($"Second saved State:{originator.GetState()}");
    
            Console.ReadKey();
        }
    }
    

    总结

    备忘录模式常用于数据的可回退操作,这样能解决一些义务处理的误操作。为了节省内存,可使用 原型模式+备忘录模式 的方式。

  • 相关阅读:
    IG GROUP开源RESTdoclet项目
    Visual Studio 2012 Update 1抢先看
    使用 Windows Azure 移动服务将云添加到您的应用
    WMF 3.0 RTM(包含PowerShell 3.0 )业已发布
    Node.js 0.9.2 发布(非稳定版)
    vsftpd 3.0.1 正式版发布
    Piggydb 6.2 发布,个人知识库管理
    Apache Commons Codec 1.7 发布
    Notepad++ 6.1.8 正式版发布
    gWaei 3.6.0 发布,英日词典
  • 原文地址:https://www.cnblogs.com/hippieZhou/p/10093574.html
Copyright © 2011-2022 走看看