PHP设计模式学习笔记: 备忘录模式(Memento)

jopen 10年前

// 阅读器类  class BookReader {          private $title;         private $page;          function __construct($title_in, $page_in) {        $this->setPage($page_in);        $this->setTitle($title_in);      }        public function getPage() {        return $this->page;      }            public function setPage($page_in) {        $this->page = $page_in;      }      public function getTitle() {        return $this->title;      }            public function setTitle($title_in) {        $this->title = $title_in;      }  }    // 备忘阅读器类的类  class BookMark {          private $title;          private $page;          function __construct(BookReader $bookReader) {        $this->setPage($bookReader);        $this->setTitle($bookReader);            }        public function getPage(BookReader $bookReader) {        $bookReader->setPage($this->page);      }        public function setPage(BookReader $bookReader) {        $this->page = $bookReader->getPage();      }          public function getTitle(BookReader $bookReader) {        $bookReader->setTitle($this->title);      }            public function setTitle(BookReader $bookReader) {        $this->title = $bookReader->getTitle();      }      }          writeln('开始测试备忘录模式');    writeln('');       $bookReader = new BookReader('哈利波特与火焰杯','103');    $bookMark = new BookMark($bookReader);       writeln('(最开始的时候) bookReader 的标题是: '.$bookReader->getTitle());    writeln('(最开始的时候) bookReader 的页码是: '.$bookReader->getPage());       $bookReader->setPage("104");    $bookMark->setPage($bookReader);    writeln('(翻过去一页后) bookReader 的页码是: '.$bookReader->getPage());        $bookReader->setPage('2005');  //oops! a typo 突然翻得太快了    writeln('(打字错误,翻得太快了) bookReader 的页码是: '.$bookReader->getPage());           print_r($bookMark);    /* $bookMark仍然存储着page的原始状态  BookMark Object  (      [title:BookMark:private] => 哈利波特与火焰杯      [page:BookMark:private] => 104  )    */      print_r($bookReader);    /* $bookReader的页码状态已经改变  BookReader Object  (      [title:BookReader:private] => 哈利波特与火焰杯      [page:BookReader:private] => 2005  )    */      // 用备忘录类来重设页码,即用备忘录类备忘下来的状态信息重设一个类的状态值    $bookMark->getPage($bookReader);    writeln('(回到翻回去一页后) bookReader 的页码是: '.$bookReader->getPage());        writeln('');      writeln('结束测试备忘录模式');      function writeln($line_in) {      echo $line_in.PHP_EOL;    }
结果:
开始测试备忘录模式    (最开始的时候) bookReader 的标题是: 哈利波特与火焰杯  (最开始的时候) bookReader 的页码是: 103  (翻过去一页后) bookReader 的页码是: 104  (打字错误,翻得太快了) bookReader 的页码是: 2005  (回到翻回去一页后) bookReader 的页码是: 104    结束测试备忘录模式