设计模式-备忘录模式

概述

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

输出结果:

当前操作:斜体

撤销一次操作:下划线

撤销两次操作:加粗

相关推荐
咖啡八杯1 天前
GoF设计模式——备忘录模式
java·后端·spring·设计模式
槑有老呆1 天前
从 Prompt Engineering 到 Harness Engineering:AI 编程的下一次跃迁
设计模式
HjhIron2 天前
从Prompt到Context:大模型应用开发的范式转移
设计模式·aigc·ai编程
咖啡八杯3 天前
GoF设计模式——中介者模式
java·后端·spring·设计模式
hez20103 天前
在 .NET 上构建超大托管数组
c#·.net·.net core·gc·clr
胡萝卜术4 天前
从“分数打架”到“排名投票”:为什么你的ChatBI必须用RRF?
算法·设计模式·面试
亦暖筑序4 天前
Java 8老系统Browser Agent实战:三层拦截把AI操作后台变成可审计流程
java·后端·设计模式
青禾网络7 天前
Web 前端如何接入 AI 音效生成:从零到可用的完整方案
人工智能·设计模式
ZJPRENO8 天前
吃透软件开发六大设计原则,告别烂代码
设计模式
咖啡八杯8 天前
GoF设计模式——命令模式
java·设计模式·架构