设计模式-备忘录模式

概述

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

输出结果:

当前操作:斜体

撤销一次操作:下划线

撤销两次操作:加粗

相关推荐
geovindu7 小时前
rust: Timing Functions Pattern
开发语言·后端·设计模式·rust·计时函数模式·性能分析型模式
zdr尽职尽责3 天前
UnityCli 兼容2022版本
ui·unity·ai·c#·游戏引擎
BruceNeter4 天前
C# winform卡死问题分析1——线程池子线程创建句柄
c#·.net
Mh5 天前
我是如何设计品牌站组件库的?
前端·css·设计模式
是2的10次方啊6 天前
设计模式与生活·总论:AI 能替你砌墙,替不了你打地基
设计模式
何以解忧唯有撸码6 天前
开源】当桌面图标开始打台球:我用 WinForms 做了一桌“真的”台球
c#·winform·自定义控件·gdi
dahaihua3336 天前
用 SysML 表达航电系统架构(附建模示例)
设计模式·重构·系统架构·集成测试·需求分析·学习方法
国家一级摸鱼选手6 天前
[Unity]几何碰撞检测:SAT 分离轴定理详解(从数学原理到 C# 实现)
unity·c#·游戏引擎·分离轴定理(sat)·多边形相交
汤姆宝库7 天前
BPE分词器的完整实现:字节对合并与词表构建
开发语言·人工智能·c#
Risehuxyc7 天前
C# 发展历史
开发语言·c#