备忘模式

<?php

//备忘类
class Memento
{
    public $ore;//水晶矿
    public $gas;//气矿
    public $troop;//玩家所有的部队对象
    public $building;//玩家所有的建筑对象
    //构造方法,参数为要保存的玩家的对象,这里强制参数的类型为Player类
    public function __construct(Player $player)
    {
        $this->ore = $player->ore;//保存这个玩家的水晶矿
        $this->gas = $player->gas;//保存这个玩家的气矿
        $this->troop = $player->troop;//保存这个玩家所有的部队对象
        $this->building = $player->building;//保存这个玩家所有的建筑对象
    }
}

//玩家的类
class Player
{
    public $ore;//水晶矿
    public $gas;//气矿
    public $troop;//玩家所有的部队对象
    public $building;//玩家所有的建筑对象
    //保存这个玩家的备忘对象
    public function getMemento()
    {
        return new Memento($this);
    }
    //用这个玩家的备忘对象来恢复这个玩家,这里强制参数的类型为Memento类
    public function restore(Memento $m)
    {
        $this->ore = $m->ore;//水晶矿
        $this->gas = $m->gas;//气矿
        $this->troop = $m->troop;//玩家所有的部队对象
        $this->building = $m->building;//玩家所有的建筑对象
    }
}



$p1 = new Player();//制造一个玩家
$p1->ore = 100;//假设他现在采了100水晶矿
echo $p1->ore;

echo '<br>';

$m = $p1->getMemento();//我们先保存游戏,然后继续玩游戏
$p1->ore = 200;//假设他现在采了200水晶矿
echo $p1->ore;

echo '<br>';

$p1->restore($m);//我们现在载入原来保存的游戏
echo $p1->ore;//输出水晶矿,可以看到已经变成原来保存的状态了

echo '<br>';

?>
原文地址:https://www.cnblogs.com/jiufen/p/5018614.html