码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-05-17 18:30:26      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:

  技术分享

  技术分享

游戏进度备忘示例:

  技术分享

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信息还原到前一状态。

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

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

标签:

原文地址:http://www.cnblogs.com/walden1024/p/4510129.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!