php設計モードの観察者モード

6917 ワード

<?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
" ); } } 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"); ?>