PHP设计模式之观察者模式实现DEMO
<?php
/**
* Jiania之观察者模式实现DEMO
*
* @package SPL
* @subpackage SPL_SpLObserver
* @author Jiania J Hung<jiania@gmail.com>
* @since PHP5.1.x
* @copyright http://www.jiania.com
*
*/
class boy implements SplObserver
{
private $name;
public function __construct($name)
{
$this->name=$name;
}
public function update(SplSubject $subject)
{
echo $this->name.” Says:I love you./n”;
}
}
class girl implements SplObserver
{
private $name;
public function __construct($name)
{
$this->name=$name;
}
public function update(SplSubject $subject)
{
echo $this->name.”Says:I love you./n”;
}
}
class sweetie implements SplSubject
{
private $name;
private $people;
private $state;
public function __construct($name)
{
$this->people=new SplObjectStorage();
$this->name=$name;
}
public function attach(SplObserver $observer)
{
$this->people->attach($observer);
}
public function detach(SplObserver $observer)
{
$this->people->detach($observer);
}
public function notify()
{
foreach ($this->people as $person)
{
$person->update($this);
}
}
function count()
{
return $this->people->count();
}
function contains($obj)
{
return $this->people->contains($obj);
}
public function getState()
{
return $this->state;
}
public function setState($state)
{
return $this->state=$state;
}
public function getName()
{
return $this->name.”/n”;
}
}
$sweetie=new sweetie(’Jiania family’);
$boy=new boy(’jiania’);
$girl=new girl(’dreamer’);
$sweetie->attach($boy);
$sweetie->attach($girl);
echo $sweetie->getState();
$sweetie->notify();