標籤:style blog class code c http
第一次寫部落格,大家多多關照!歡迎拍磚哦!
我也剛學設計模式,所以記錄下來。
?
| 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 |
<?php class person{ public $name; public $birthday; public function __set($name,$value){ if(isset($this->$name)) $this->$name=$value; } public function __get($name){ if(isset($this->$name)) return $this->$name; } } //觀察者類實現SplSubject介面,SplSubject是php內建介面 class PersonSubject implements SplSubject{ public $observers,$person; public function __construct(person $person){ $this->observers = new SplObjectStorage(); $this->person=$person; } //增加一個觀察者 public function attach(SplObserver $observers){ $this->observers->attach($observers); } //刪除一個觀察者 public function detach(SplObserver $observers){ $this->observers->detach($observers); } //達到條件時,通知觀察者 public function notify(){ foreach($this->observers as $observer){ $observer->update($this); } } //返回被觀察者執行個體,供觀察者處理 public function getPerson(){ return $this->person; } } //觀察者實現SplObserver介面,SplObserver是php內建介面 class fatherObserver implements SplObserver{ //條件達到時,執行的動作 public function update(SplSubject $splsubject){ $person=$splsubject->getPerson(); echo $person->name.‘ 生日快樂,我是爸爸!‘; } } class motherObserver implements SplObserver{ public function update(SplSubject $splsubject){ $person=$splsubject->getPerson(); echo $person->name.‘ 生日快樂,我是媽媽!‘; } } class sisterObserver implements SplObserver{ public function update(SplSubject $splsubject){ $person=$splsubject->getPerson(); echo $person->name.‘ 生日快樂,我是姐姐!‘; } } //執行個體化小明 $xiaoming=new person(); $xiaoming->name=‘小明‘; $xiaoming->birthday=‘0512‘; //綁定觀察者 $subject=new PersonSubject($xiaoming); $subject->attach(new fatherObserver); $subject->attach(new motherObserver); $subject->attach(new sisterObserver); //如果小明生日到了,通知觀察者 $date=date(‘md‘,time()); if($xiaoming->birthday==$date){ $subject->notify(); } ?> |
輸出
大家自己看吧,項目中我也沒用到觀察者模式,鬱悶!