设计模式-备忘录模式

概述

备忘录模式也是一种行为型的设计模式,其主要的功能是存储和撤销的功能,可以恢复之前的状态,在实际的开发中,几乎是必不可少的功能,现在几乎所有的软件都少不了撤销的功能,如果没有撤销,那在误操作后会很麻烦,那如何实现这个功能呢,如果有这方面开发经历的同学肯定想到可以使用栈来存储,将操作都存储在栈中,操作后就入栈,撤销就出栈,这样做当然是可以的,那接下来就结合实际的例子来学习一下这部分的内容该如何编写吧,以下是模拟Word的操作。


例子:模拟Word的操作,在用户使用 加粗,下划线,斜体后使用撤销操作后可以返回之前的操作。

备忘录模式

cs 复制代码
using System.Numerics;
using static POC;

internal class Program
{
    private static void Main(string[] args)
    {
        WordEditor editor = new WordEditor();//创建word编辑器
        Caregiver caregiver = new Caregiver();//创建看护者

        editor.operate = "加粗";
        caregiver.SaveMemoType(editor.Save());
        editor.operate = "下划线";
        caregiver.SaveMemoType(editor.Save());
        editor.operate = "斜体";
        Console.WriteLine($"当前操作:{editor.operate}");
        editor.Restore(caregiver.RestoreMemoType());
        Console.WriteLine($"撤销一次操作:{editor.operate}");
        editor.Restore(caregiver.RestoreMemoType());
        Console.WriteLine($"撤销两次操作:{editor.operate}");
    }
    public class MemoType//备忘录类
    {
        public string operate { get; set; }
        public MemoType(string OP)
        {
            operate = OP;
        }
    }
    public class WordEditor//Word编辑器(发起人)
    {
        public string operate { get; set; }
        public MemoType Save()
        {
            return new MemoType(operate);
        }
        public void Restore(MemoType memoType)
        {
            operate = memoType.operate;
        }
    }
    public class Caregiver//监护者
    {
        private readonly Stack<MemoType> memo = new Stack<MemoType>();
        public void SaveMemoType(MemoType memoType)
        {
            memo.Push(memoType);
        }
        public MemoType RestoreMemoType()
        {
            return memo.Pop();
        }
    }
}

输出结果:

当前操作:斜体

撤销一次操作:下划线

撤销两次操作:加粗

相关推荐
软件黑马王子2 小时前
C#初级教程(4)——流程控制:从基础到实践
开发语言·c#
黑不溜秋的3 小时前
C++ 设计模式 - 策略模式
c++·设计模式·策略模式
付聪12105 小时前
策略模式介绍和代码示例
设计模式
ThereIsNoCode6 小时前
「软件设计模式」状态模式(State)
设计模式·状态模式
水煮庄周鱼鱼7 小时前
C# 入门简介
开发语言·c#
软件黑马王子7 小时前
Unity游戏制作中的C#基础(6)方法和类的知识点深度剖析
开发语言·游戏·unity·c#
小猫猫猫◍˃ᵕ˂◍8 小时前
备忘录模式:快速恢复原始数据
android·java·备忘录模式
Nicole Potter8 小时前
请说明C#中的List是如何扩容的?
开发语言·面试·c#
gu2010 小时前
c#编程:学习Linq,重几个简单示例开始
开发语言·学习·c#·linq
菜鸟一枚在这12 小时前
深入理解设计模式之代理模式
java·设计模式·代理模式