备忘录模式

本文介绍了备忘录模式的基本概念及其实现方式,通过游戏人物角色的状态保存与恢复实例展示了如何在不破坏封装性的前提下捕获并保存对象的内部状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

备忘录模式(Memento Pattern)又叫做快照模式(Snapshot Pattern)或Token模式,是GoF的23种设计模式之一,属于行为模式。

定义(源于GoF《设计模式》):在不破坏封闭的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态

涉及角色
1.Originator(发起人):负责创建一个备忘录Memento,用以记录当前时刻自身的内部状态,并可使用备忘录恢复内部状态。Originator可以根据需要决定Memento存储自己的哪些内部状态。
2.Memento(备忘录):负责存储Originator对象的内部状态,并可以防止Originator以外的其他对象访问备忘录。备忘录有两个接口:Caretaker只能看到备忘录的窄接口,他只能将备忘录传递给其他对象。Originator却可看到备忘录的宽接口,允许它访问返回到先前状态所需要的所有数据。
3.Caretaker(管理者):负责备忘录Memento,不能对Memento的内容进行访问或者操作。

个人理解

在一个类(发起人)中,需要定义一个变量来存储这个类的某些属性在发生变化前的值,因此可以在Originato中定义一个Memento变量,而省去Caretaker这个类

Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MemoDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            GameRole role = new GameRole(100,10000,1000);

            role.Show();
            role.Store();
            role.Fight();
            role.Show();
            role.Reset();
            role.Show();

        }
    }

    public class GameRole
    {
        public int HP;
        public int Attack;
        public int Defense;
        public Memo memo;

        public GameRole(int _hp, int _attack, int _def)
        {
            this.HP = _hp;
            this.Attack = _attack;
            this.Defense = _def;
        }

        public void Fight()
        {
            Console.WriteLine("战斗结束");
            this.HP = 0;
            this.Attack = 0;
            this.Defense = 0;
        }

        public void Show()
        {
            Console.WriteLine("显示当前状态");
            Console.WriteLine("当前血量{0}", this.HP);
            Console.WriteLine("当前攻击力{0}", this.Attack);
            Console.WriteLine("当前防御力{0}", this.Defense);
            Console.WriteLine();
        }

        public void Store()
        {
            this.memo = new Memo(this.HP, this.Attack, this.Defense);
        }

        public void Reset()
        {
            if(this.memo == null)
            {
                return;
            }

            Console.WriteLine("状态重置");

            this.HP = this.memo.HP;
            this.Attack = this.memo.Attack;
            this.Defense = this.memo.Defense;
        }

    }

    public class Memo
    {
        public int HP;
        public int Attack;
        public int Defense;

        public Memo(int _hp, int _attack, int _def)
        {
            this.HP = _hp;
            this.Attack = _attack;
            this.Defense = _def;
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值