设计模式——备忘录模式

说明

示例

下面看下备忘录模式的代码实现

class Original{
private string $value;

public function __construct(string $value){
$this->value = $value;
}

public function getValue(): string{
return $this->value;
}

public function setValue(string $value){
$this->value = $value;
}

public function createMemento(): Memento{
return new Memento($this->value);
}

public function restoreMemento(Memento $memento){
$this->value = $memento->getValue();
}
}

class Memento{
private string $value;

public function __construct(string $value){
$this->value = $value;
}

public function getValue(): string{
return $this->value;
}

public function setValue(string $value){
$this->value = $value;
}
}

class Storage{
private Memento $memento;

public function __construct(Memento $memento){
$this->memento = $memento;
}

public function getMemento(): Memento{
return $this->memento;
}

public function setMemento(Memento $memento){
$this->memento = $memento;
}
}


// 调用
$origi = new Original("egg");
$storage = new Storage($origi->createMemento());

echo "初始化状态为:" . $origi->getValue() . PHP_EOL;
$origi->setValue("niu");
echo "修改后的状态为:" . $origi->getValue() . PHP_EOL;

$origi->restoreMemento($storage->getMemento());
echo "恢复后的状态为:" . $origi->getValue() . PHP_EOL;
/**
* output:
* 初始化状态为:egg
* 修改后的状态为:niu
* 恢复后的状态为:egg
*
*/


总结


文章作者: Crazy Boy
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Crazy Boy !
赏

留言

想法、疑问或勘误,都可以写在这里。留言会公开显示。

正在准备留言区…

 上一篇
设计模式——外观模式 设计模式——外观模式
说明 外观模式是为了解决类与类之家的依赖关系的,像spring一样,可以将类和类之间的关系配置到配置文件中,而外观模式就是将他们的关系放在一个Facade类中,降低了类类之间的耦合度,该模式中没有涉及到接口,看下类图:(我们以一个计算机的启
2022-05-19
下一篇 
设计模式——工厂方法模式 设计模式——工厂方法模式
说明 创建一个工厂接口和创建多个工厂实现类,这样一旦需要增加新的功能,直接增加新的工厂类就可以了,不需要修改之前的代码。 示例 下面看下工厂方法模式的代码实现 总结 优点:扩展性好。如果需要添加个企业微信推送,只需做一个实现类,实现Send
2022-05-19