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 |
<?php //观察者模式,通俗的讲就是在希望被观察的类中定义一个容器存放允许观察它的类, //并约定一些方法来注册(attach)、注销(detach)、通知(notify)观察者类。 //观察者类型定义一个update方法,当接受到通知后做相应的修改 //demo如下,实际应用中type是需要约定的,如果通知的对象是一类,则不需要type interface IObject{ public function attach($type, IObserver $observer); public function detach($type, IObserver $observer); public function notify($type); } class Jay implements IObject{ protected $oblist = array(); protected $name = '周杰伦'; public function attach($type, IObserver $observer){ $this->oblist[$type][] = $observer; } public function detach($type, IObserver $observer){ if (isset($this->oblist[$type])) { $key = array_search($observer, $this->oblist[$type]); if ($key !== false) { unset($this->oblist[$type][$key]); } } } public function notify($type){ if (isset($this->oblist[$type])) { foreach ($this->oblist[$type] as $observer) { $observer->update($this); } } } public function album(){ echo '我要发专辑了...<br>'; $this->notify('album'); } public function marry(){ echo '我要结婚了...<br>'; $this->notify('marry'); } public function getName(){ return $this->name; } } interface IObserver{ public function update(IObject $object); } class Fans implements IObserver{ public function update(IObject $object) { echo $object->getName() . '发专辑了,我要去购买<br>'; } } class Friend implements IObserver{ public function update(IObject $object) { echo $object->getName() . '要结婚了,我要去参加<br>'; } } class Company implements IObserver{ public function update(IObject $object) { echo $object->getName() . '发专辑了,赶紧做宣传<br>'; } } $jay = new Jay(); $company = new Company(); $jay->attach('album', new Fans()); $jay->attach('album', $company); $jay->attach('marry', new Friend()); $jay->album(); $jay->marry(); $jay->detach('album', $company); $jay->album(); |