行为型设计模式->备忘录模式

2018-12-06  本文已影响0人  liu66_net
<?php
//备忘录模式

//编辑器
class Edit
{
    public $act;

    public $content;

//保存状态
    public function saveState(Caretaker $caretaker)
    {
        $caretaker->add(new Memento($this->act,$this->content));
    }
    //恢复状态
    public function recoveryState(Memento $memento)
    {
        $this->act = $memento->act;
        $this->content = $memento->content;
    }

    public function modify($act,$content)
    {
        $this->act = $act;
        $this->content = $content;
    }

    public function show()
    {
        echo "操作:".$this->act."\r\n";
        echo "内容:".$this->content."\r\n";
    }



}

//存储
class Memento
{
    public $act;
    public $content;

    public function __construct($act,$content)
    {
        $this->act = $act;
        $this->content = $content;
    }
}

//管理类
class Caretaker
{
    public $data = array();

    public function add(Memento $memento)
    {
        $this->data[] = $memento;
    }

    //获取上一个
    public function getLast()
    {
        $len = count($this->data);

        if($len < 1)
        {
            return;
        }

        return $this->data[$len - 1];
    }
}

//动作

class Client
{
    public static function main($argv)
    {
        $edit = new Edit();
        $caretaker = new Caretaker();

        $edit->modify('插入abc','abc');
        $edit->saveState($caretaker);

        $edit->modify('插入d','abcd');
        $edit->saveState($caretaker);

        $edit->modify('删除c','abd');
        $edit->saveState($caretaker);

        $edit->modify('插入e','abde');

        //恢复上一个状态
        $edit->recoveryState($caretaker->getLast());

        $edit->show();
    }
}
Client::main($argv=0);

上一篇下一篇

猜你喜欢

热点阅读