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

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());

  

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

最新文章

  1. Spring任务调度之Quartz
  2. C++ 中超类化和子类化常用API
  3. 用refresh控制浏览器定时刷新
  4. centos7 挂载数据盘
  5. [MAC ] Mac-OSX下安装Git
  6. java 格式化时间
  7. mysql的日期存储字段比较int,datetime,timestamp区别
  8. C# 添加.DLL 出错的解决方法
  9. java程序员应该掌握的技能
  10. devexpress中应用于girdviw中HtmlDataCellPrepared事件与CellEditorInitialize事件的区别
  11. MongoDB的安装配置
  12. Mac下使用Fiddler
  13. Eclipse项目 迁移到 Intellj IDEA
  14. ASP .Net Core 使用 Dapper 轻型ORM框架
  15. hdu 1542 Atlantis(段树&扫描线&面积和)
  16. vuejs学习笔记(2)--属性,事件绑定,ajax
  17. Mac实用操作技巧(四)
  18. Visual studio 2017 未能正确加载“Microsoft.VisualStudio.Editor.Implementation.EditorPackage”包
  19. 【原创】C# API 未能创建 SSL/TLS 安全通道 问题解决
  20. windows服务加定时器实现

热门文章

  1. WPF第三方控件盘点
  2. codevs 1085
  3. python中的三元表达式
  4. 前段基础JavaScript
  5. 使用maven进行Javadoc下载
  6. (七)MySQL数据操作DQL:多表查询2
  7. Nodejs获取Azure Active Directory AccessToken
  8. npm命令要记
  9. HDU 多校1.10
  10. golang笔记:cookie