zoukankan      html  css  js  c++  java
  • B9:备忘录模式 Memento

    在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态.这样以后就可以将该对象恢复到原先保存的状态

    UML:

    示例代码:

    class Role
    {
        private $hp;
        private $attack;
    
        public function __construct($hp, $attack)
        {
            $this->hp = $hp;
            $this->attack = $attack;
        }
    
        public function fight()
        {
            $this->hp = 0;
            echo "开始打Boos,血条到了{$this->hp}" . PHP_EOL;
        }
    
        // 创建一个备份
        public function createMemento()
        {
            return new RoleMemento($this->hp, $this->attack);
        }
    
        public function restoreMemento(RoleMemento $memento)
        {
            $this->hp = $memento->getHp();
            $this->attack = $memento->getAttack();
            echo "又恢复了, 血条到了{$this->hp};攻击力到了{$this->attack}";
        }
    }
    
    class RoleMemento
    {
        private $hp;
        private $attack;
    
        public function __construct($hp, $attack)
        {
            $this->hp = $hp;
            $this->attack = $attack;
        }
    
        public function __call($name, $args)
        {
            $name = strtolower(str_replace('get', '', $name));
            if (property_exists($this, $name)) {
                return $this->$name;
            }
        }
    }
    
    class MementoAdmin
    {
        private $memento;
    
        public function setMemento(RoleMemento $roleMemento)
        {
            $this->memento = $roleMemento;
        }
    
        public function getMemento()
        {
            return $this->memento;
        }
    }
    
    $role = new Role(5900, 1500);
    
    $admin = new MementoAdmin();
    $admin->setMemento($role->createMemento()); // 创建一个备份
    
    $role->fight();
    
    $role->restoreMemento($admin->getMemento());
    

      

    如果只有一个备忘录,可以取消备忘录管理者.

  • 相关阅读:
    条件判断和循环
    list 和tuple的使用
    python的五大数据类型
    简单的一个程序,猜字游戏
    redhat7 nfs的配置以及auto自动挂载
    nmcli添加网卡 并且修改设备名字 添加IP地址
    RHEL7 系统ISCSI存储环境搭建
    Java分布式锁
    24个Jvm面试题总结及答案
    最新天猫3轮面试题目:虚拟机+并发锁+Sql防注入+Zookeeper
  • 原文地址:https://www.cnblogs.com/itfenqing/p/7791699.html
Copyright © 2011-2022 走看看