Home >Backend Development >PHP Tutorial >PHP设计模式之备忘录模式

PHP设计模式之备忘录模式

WBOY
WBOYOriginal
2016-06-23 13:06:00885browse

备忘录模式属于行为型模式,何为行为型模式,即行为型模式设计到算法和对象间的职责分配,不仅描述对象或类的模式,还描述它们之间的通信方式,刻划了运行时难以跟踪的复杂的控制流,它们将你的注意力从控制流转移到对象间的关系上来。行为型类模式采用继承机制在类间分派行为

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

个人举例:

1 看书的书签

2 消息盒子

/**

* 发起角色

* 备忘录角色

* 管理备忘录角色

*/

namespace haibao\design\web\view\design;

use haibao\design\web\common\design\memento\Originator;

use haibao\design\web\common\design\memento\Caretaker;

class Memento extends \haibao\design\web\view\Base{

protected function preRender(){

header("Content-type: text/html; charset=utf-8");

$originator = new Originator();

$originator->state = "ON";

$originator->show();

$caretaker = new Caretaker();

$caretaker->setMemento($originator->createMemento());

$originator->state = "OFF";

$originator->show();

$originator->setMemento($caretaker->getMemento());

$originator->show();

}

}

/**

* 管理角色

*/

namespace haibao\design\web\common\design\memento;

class Caretaker{

private $memento;

public function setMemento($memento){

$this->memento = $memento ;

}

public function getMemento(){

return $this->memento;

}

}

/**

* 备忘录角色

*/

namespace haibao\design\web\common\design\memento;

class Mementor{

private $state;

public function __construct($state){

$this->state = $state;

}

public function getState(){

return $this->state;

}

}

/**

* 发起人角色

*/

namespace haibao\design\web\common\design\memento;

class Originator{

public $state;

public function createMemento(){

return new Mementor($this->state);

}

public function setMemento(Mementor $memento){

$this->state = $memento->getState();

}

public function show(){

echo "
State=".$this->state;

}

}

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn