-
Notifications
You must be signed in to change notification settings - Fork 0
/
mediator.php
127 lines (103 loc) · 2.63 KB
/
mediator.php
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
<?php
/**
* Created by PhpStorm.
* User: netAir
* Date: 17-7-19
* Time: 下午4:46
*/
class OldCD
{
public $band;
public $title;
public function save()
{
//假装修改了将数据写回到数据库
var_dump($this);
}
public function changeBandName($newName)
{
$this->band = $newName;
$this->save();
}
}
//为了添加MP3归档类(MP3Archive),并且再更改MP3归档的同时修改CD对象,需要修改原有CD类
abstract class Base
{
public $band = '';
public $title = '';
protected $mediator;
abstract public function save();
abstract public function changeBandName($newName);
}
class CD extends Base
{
public function __construct(MusicContainerMediator $mediator = null)
{
$this->mediator = $mediator;
}
public function save()
{
//还是得假装修改了将数据写回到数据库
var_dump($this);
}
public function changeBandName($newName)
{
if (!is_null($this->mediator)) {
$this->mediator->change($this, ['band' => $newName]);
}
$this->band = $newName;
$this->save();
}
}
class MP3Archive extends Base
{
public function __construct(MusicContainerMediator $mediator = null)
{
$this->mediator = $mediator;
}
public function save()
{
//还是得假装修改了将数据写回到数据库
var_dump($this);
}
public function changeBandName($newName)
{
if (!is_null($this->mediator)) {
$this->mediator->change($this, ['band' => $newName]);
}
$this->band = $newName;
$this->save();
}
}
class MusicContainerMediator
{
protected $containers = [];
public function __construct()
{
$this->containers[] = 'CD';
$this->containers[] = 'MP3Archive';
}
public function change(Base $originalObject, array $newValue)
{
$title = $originalObject->title;
$band = $originalObject->band;
foreach ($this->containers as $container) {
if (!($originalObject instanceof $container)) {
$object = new $container;
$object->title = $title;
$object->band = $band;
foreach ($newValue as $key => $value) {
$object->$key = $value;
}
$object->save();
}
}
}
}
$titleFromDB = 'Waste of a Rib';
$bandFromDB = 'Never Again';
$mediator = new MusicContainerMediator();
$cd = new CD($mediator);
$cd->title = $titleFromDB;
$cd->band = $bandFromDB;
$cd->changeBandName('Maybe Once More');