随笔-3  评论-2  文章-0  trackbacks-0

UML图


代码:
<?php
class Customer{
 private $id ;
 private $name ;
 private $address ;
 private $tel ;
 private static $observers = array() ;
 /**
  * @return the $id
  */
 public function getId() {
  return $this->id;
 }

 /**
  * @return the $name
  */
 public function getName() {
  return $this->name;
 }

 /**
  * @return the $address
  */
 public function getAddress() {
  return $this->address;
 }

 /**
  * @return the $tel
  */
 public function getTel() {
  return $this->tel;
 }

 /**
  * @param $id the $id to set
  */
 public function setId($id) {
  $this->id = $id;
 }

 /**
  * @param $name the $name to set
  */
 public function setName($name) {
  $this->name = $name;
 }

 /**
  * @param $address the $address to set
  */
 public function setAddress($address) {
  $this->address = $address;
 }

 /**
  * @param $tel the $tel to set
  */
 public function setTel($tel) {
  $this->tel = $tel;
 }
 /**
  *
  * @param Observer $observer
  */
 public static function attach($observer){
  if (!in_array($observer , self::$observers)){
   self::$observers[] = $observer ;
  }
 }
 /**
  *
  * @param Observer $observer
  */
 public static function detach($observer){
  foreach (self::$observers as $k => $item) {
   if ($item == $observer){
    unset(self::$observers[$k]) ;
   }
  }
 }
 /**
  * 通知所有的观察者
  */
 public function notify(){
  foreach (self::$observers as $observer) {
   $observer->update($this) ;
  }
 }
}
interface Observer{
 /**
  *
  * @param Customer $customer
  */
 public function update($customer) ;
 
}

class Address implements Observer{
 private $address = 'tianhe' ;
 /**
  *
  * @param Customer $customer
  */
 public function update($customer){
  if ($customer->getAddress() != $this->address){
   echo '地址变了...................' ;
   echo '<br>' ;
  }
 }
}

class Tel implements Observer{
 private $tel = 13602413192 ;
 /**
  *
  * @param Customer $customer
  */
 public function update($customer){
  if ($customer->getTel() != $this->tel){
   echo '电话变了...............' ;
   echo '<br>' ;
  }
 }
}
header("Content-Type:text/html;charset=utf-8") ;
$address = new Address() ;
$tel = new Tel() ;
Customer::attach($address) ;
Customer::attach($tel) ;

$customer = new Customer() ;
$customer->notify() ;

?>

本模式特性:
1.被观察者不需要知道自己被那些对象(观察者)观察着,观察者知道自己要观察谁(调用被观察者的attach()方法)
2.被观察者只需要在属性发生改变时,调用notify()方法,则所有在观察自己的对象都知道做出何种反应(观察者通过update()来做出反应)

posted on 2010-06-14 23:54 fanyh 阅读(198) 评论(0)  编辑 收藏 引用 所属分类: PHP
只有注册用户登录后才能发表评论。