观察者模式
定义了对象之间的依赖,一旦其中一个对象的状态发生改变,依赖它的对象都会收到通知。
实例

<?php class Job { public $title; public function __construct($title) { $this->title = $title; } } class JobSeeker { public $name; public function __construct($name) { $this->name = $name; } public function onJobPosted(Job $job) { echo 'Hi ' . $this->name . '!New job posted:' . $job->title.PHP_EOL; } } class JobPostings { public $jobSeekers = []; private function notify(Job $job) { foreach ($this->jobSeekers as $jobSeeker) { $jobSeeker->onJobPosted($job); } } public function attach(JobSeeker $jobSeeker){ $this->jobSeekers[]=$jobSeeker; } public function addJob(Job $job){ $this->notify($job); } } $john=new JobSeeker('John'); $jack=new JobSeeker('Jack'); $posting=new JobPostings(); $posting->attach($john); $posting->attach($jack); $posting->addJob(new Job('teacher'));