php 设计模式之观察者模式

<?php

//观察者: 负责信息的变化。
interface IObserver{
 function onChanged($sender,$args);
}

//被观察者:加入到被观察者队列中,实现被观察
interface IObservable{
 function addObserver($observer);
}


// 实现被观察,
class UserList implements IObservable {

 //定义观察者集合
 private $_observers = array();
 
 //增加用户,调用观察者
 public function addCustomer($name){
 
   foreach ($this->_observers as $obs){
     
   $obs->onChanged($this,$name);
   $obs->sendMessage($this,$message);
  }
  //do something
 }
 
 // 执行观察者的方法
 public function sendMessage($message){
  
  foreach ($this->_observers as $obs)
  {
    $obs->sendMessage($this,$message);
  }
 }
 
 //在被观察者 引入观察者
 public function addObserver($observer){
  $this->_observers[] = $observer;
 }
}


//观察者:是要改变的信息
class UserListLogger implements IObserver
{
  public function onChanged( $sender, $args )
  {
   if($args ==='json'){
    echo 'JSON you are pig';
   }else{
     echo( "'$args' added to user list\n" );
   }
  }
  
  public function sendMessage($sender,$message){
   echo $message;
  }
  
}

class Userbing implements IObserver
{
    public function onChanged($sender,$message)
    {
        if(!empty($message))
        {
            echo "我将加入....你的组织!";
        }
    }
    
    public function sendMessage($sender,$mesg)
    {
        echo $mesg;
    }
}


$ul = new UserList();
$ul->addObserver( new UserListLogger() );
$ul->addCustomer( "json" );
$ul->sendMessage( "欢迎 JSON光临" );


$ul->addObserver( new userbing());
$ul->addCustomer("hubing");
$ul->sendMessage("hello");

?>

 

posted @ 2013-09-04 16:44  北斗极星  阅读(245)  评论(0编辑  收藏  举报