Beware as it is untested.
// The event object
class DelegateObject
{
 public $InvocationString;
 public __construct( $InvocationString )
 {
  $this->InvocationString = $InvocationString;
 }
 public Invoke( )
 {
  eval($this->InvocationString);
 }
}
class EventObject extends DelegateObject
{
 public $EventSource;
 public $Listener;
 public __construct( $EventSource, $Listener, $InvocationString )
 {
  $this->EventSource = $EventSource;
  $this->Listener = $Listener;
  $this->InvocationString = $InvocationString;
 }
}
class EventDispatcher
{
 public AddListener( $EventName, $Listener, $FunctionName )
 {
  $e = new EventObject( $this, $Listener, '$this->Listener->' . $FunctionName . '($this->EventSource)' );
  $ListenerProperty = $EventName . '_Listeners';
  $this->$ListenerProperty[] = $e;
 }
 
 public FireEvent( $EventName )
 {
  $ListenerProperty = $EventName . '_Listeners';
  foreach($this->$ListenerProperty as $Listener)
  {
   $Listener->Invoke( );
  }
 }
}
// the Classes:
class SmokeAlarm extends EventDispatcher
{
 public $Location;
 
 public __construct( $Location )
 {
  $this->Location = $Location;
 }
 
 public Smoke( )
 {
  $this->FireEvent( "Smoke" );
 }
}
class HouseAlarm
{
 public Fire( $SmokeAlarm )
 {
  echo 'Fire ' . $SmokeAlarm->Location .  '!';
 }
}
$SmokeAlarm_2ndFloor = new SmokeAlarm( 'on the second floor' );
$SmokeAlarm_LivingRoom = new SmokeAlarm( 'in the living room' );
$HouseAlarm = new HouseAlarm( );
// Binding the listener
$SmokeAlarm_2ndFloor->AddListener( "Smoke", $HouseAlarm, "Fire" );
$SmokeAlarm_LivingRoom->AddListener( "Smoke", $HouseAlarm, "Fire" );
// test
$SmokeAlarm_2ndFloor->Smoke( );
$SmokeAlarm_LivingRoom->Smoke( );
woensdag 16 september 2009
Abonneren op:
Reacties (Atom)
 
