设计模式-备忘录模式

概述

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

输出结果:

当前操作:斜体

撤销一次操作:下划线

撤销两次操作:加粗

相关推荐
数据智能老司机8 小时前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机9 小时前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
mudtools11 小时前
.NET驾驭Word之力:玩转文本与格式
c#·.net
烛阴12 小时前
【TS 设计模式完全指南】懒加载、缓存与权限控制:代理模式在 TypeScript 中的三大妙用
javascript·设计模式·typescript
李广坤13 小时前
工厂模式
设计模式
唐青枫15 小时前
C#.NET 数据库开发提速秘籍:SqlSugar 实战详解
c#·.net
mudtools1 天前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
幂简集成explinks1 天前
e签宝签署API更新实战:新增 signType 与 FDA 合规参数配置
后端·设计模式·开源
大飞pkz2 天前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
努力也学不会java2 天前
【设计模式】抽象工厂模式
java·设计模式·oracle·抽象工厂模式