现在的位置: 首页 > 综合 > 正文

备忘录模式

2018年10月20日 ⁄ 综合 ⁄ 共 2227字 ⁄ 字号 评论关闭

备忘录模式(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;
        }
    }

}

抱歉!评论已关闭.