Walden1024

导航

《大话设计模式》学习笔记14:备忘录模式

  

  

游戏进度备忘示例:

  

1.Originator:

    public class GameRole
    {
        public int Vitality { get; set; }
        public int Attack { get; set; }
        public int Defense { get; set; }
        //状态显示
        public void StateDisplay()
        {
            Console.WriteLine("角色当前状态:体力 {0},攻击力 {1},防御力 {2}", Vitality, Attack, Defense);
        }
        //获得初始状态
        public void GetInitState()
        {
            Vitality = 100;
            Attack = 100;
            Defense = 100;
        }
        //战斗
        public void Fight()
        {
            Vitality = 0;
            Attack = 0;
            Defense = 0;
        }
        
        public RoleStateMemento SaveState()
        {
            return new RoleStateMemento(Vitality, Attack, Defense);
        }
        public void RecoveryState(RoleStateMemento roleStateMemento)
        {
            Vitality = roleStateMemento.Vitality;
            Attack = roleStateMemento.Attack;
            Defense = roleStateMemento.Defense;
        }
    }

2.Memento:

    public class RoleStateMemento
    {
        public int Vitality { get; set; }
        public int Attack { get; set; }
        public int Defense { get; set; }

        public RoleStateMemento(int vitality,int attack,int defense)
        {
            Vitality = vitality;
            Attack = attack;
            Defense = defense;
        }
    }

3.Caretaker:

    public class RoleStateCaretaker
    {
        public RoleStateMemento RoleStateMemento { get; set; }

    }

4.客户端代码:

    class Program
    {
        static void Main(string[] args)
        {
            GameRole gameRole = new GameRole();
            gameRole.GetInitState();
            gameRole.StateDisplay();

            RoleStateCaretaker roleStateCaretaker = new RoleStateCaretaker();
            roleStateCaretaker.RoleStateMemento = gameRole.SaveState();

            gameRole.Fight();
            gameRole.StateDisplay();

            gameRole.RecoveryState(roleStateCaretaker.RoleStateMemento);
            gameRole.StateDisplay();
        }
    }

  备忘录模式比较适用于功能比较复杂的,但需要维护或记录属性历史的类,或者需要保存的属性只是众多属性中的一小部分时,Originator可以根据保存的Memento信息还原到前一状态。

  如果某个系统中使用命令模式时,需要实现命令的撤销功能,那么命令模式可以使用备忘录模式来存储可撤销操作的状态。

posted on 2015-05-17 17:44  Walden1024  阅读(214)  评论(0编辑  收藏  举报