当对象的状态发生变化时,所有依赖于它的对象都得到通知并被自动更新。它使用的是低耦合的方式。

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
class DeleteUserSubject implements \SplSubject
{

protected SplObjectStorage $observers;


protected $data;

public function __construct()
{
$this->observers = new \SplObjectStorage();
}

public function attach(SplObserver $observer)
{
$this->observers->attach($observer);
}

public function detach(SplObserver $observer)
{
$this->observers->detach($observer);
}

public function notify()
{
foreach ($this->observers as $observer) {
$observer->update($this);
}
}

public function process()
{
$this->data = new class {
public string $name = 'wu';

public function delete()
{
echo '用户 ', $this->name, ' 被删除', PHP_EOL;
}
};

$this->data->delete();

echo '开始通知关联处理:', PHP_EOL;
$this->notify();
}

public function getName()
{
return $this->data->name;
}
}

class UserLogDeleteObserver implements \SplObserver
{

protected SplSubject $subject;

public function update(SplSubject $subject)
{
$this->subject = clone $subject;
$this->deleteUserLog();
}

public function deleteUserLog()
{
echo '删除用户', $this->subject->getName(),' 的日志', PHP_EOL;
}
}

$subject = new DeleteUserSubject();
$subject->attach(new UserLogDeleteObserver());
$subject->process();

这个模式代码稍微多一点,但是场景很经典,也很容易理解。