喜迎
春节

设计模式——备忘录模式


说明

示例

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
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 !
评 论
 上一篇
设计模式——命令模式
设计模式——命令模式
说明示例下面看下命令模式的代码实现 1234567891011121314151617181920212223242526272829303132333435363738394041// 创建接口Commandinterface Comma
2022-05-19
下一篇 
设计模式——工厂方法模式
设计模式——工厂方法模式
说明 创建一个工厂接口和创建多个工厂实现类,这样一旦需要增加新的功能,直接增加新的工厂类就可以了,不需要修改之前的代码。 示例下面看下工厂方法模式的代码实现 1234567891011121314151617181920212223242
2022-05-19
  目录
hexo