美文网首页
备忘录模式/快照模式(PHP)

备忘录模式/快照模式(PHP)

作者: 嗼念 | 来源:发表于2021-10-20 10:07 被阅读0次

    备忘录模式

    备忘录模式又称作快照模式,属于行为型设计模式。
    备忘录模式的定义
    在不违背封装原则的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,以便之后恢复对象为先前的状态。

    备忘录模式的应用场景也相对明确,主要是用来防止丢失、撤销和恢复等。主要缺点是资源消耗大,如果要保存的状态信息过多将会占用比较大的内存资源。

    使用场景:
    1、游戏的存档点、ctrl+z、棋盘类游戏的悔棋之类
    2、数据库的事务管理

    举个例子:
    有这样一道题,希望编写一个小程序,可以接收命令行的输入。用户输入文本时,程序将其追加存储在内存文本中;用户输入“:list”,程序在命令行中输出内存文本的内容;用户输入“:undo”,程序会撤销上一次输入的文本,也就是从内存文本中将上次输入的文本删除掉。

    class InputText {
        private  $text = '' ;
        //获取内容
        public function getText() {
            return $this->text ;
        }
        //新增内容
        public function append($string) {
            $this->text .= ' '.$string ;
        }
        //创建快照
        public function createSnapshot() {
            return new Snapshot($this->getText()) ;
        }
        //恢复到快照的内容
        public function restoreSnapshot($snapshot) {
            $this->text = $snapshot->getText() ;
        }
    }
    //生成快照(要被恢复的对象的状态)
    class Snapshot {
        private $text ;
        public function __construct($text) {
            $this->text = $text ;
        }
        public function getText() {
            return $this->text ;
        }
    }
    //快照列表维护,用栈的方式实现
    class SnapshotHolder {
        private $snapshots = [] ;
        public function popSnapshot() {
            return array_pop($this->snapshots) ;
        }
        public function pushSnapshot($snapshot) {
            array_push($this->snapshots, $snapshot) ;
        }
    }
    class ApplicationMain {
        public function __construct() {
            $this->InputText = new InputText() ;
            $this->SnapshotHolder = new SnapshotHolder() ;
        }
        public function main ($string) {
            $string = trim($string) ;
            if ($string == ':list') {
                echo "输出:".$this->InputText->getText() . "\r\n" ;
            } elseif($string == ':undo') {
                $snapshot = $this->SnapshotHolder->popSnapshot() ;
                $this->InputText->restoreSnapshot($snapshot) ;
            } else {
                $this->SnapshotHolder->pushSnapshot($this->InputText->createSnapshot()) ;
                $this->InputText->append($string) ;
            }
        }
    }
    $demo = new ApplicationMain() ;
    while (!feof(STDIN)) {
        $line = fread(STDIN, 1024) ;
        $demo->main($line) ;
    }
    

    相关文章

      网友评论

          本文标题:备忘录模式/快照模式(PHP)

          本文链接:https://www.haomeiwen.com/subject/tdxaoltx.html