|
[PHP]
<?php
/*
* 作者:岳信明
* Date: 2009-01-09
*/
abstract class Subject
{
private $SubEvent;
public function FireAway()
{
if (is_array($this->SubEvent))
{
foreach($this->SubEvent as $x)
{
try {
$x->Response();
} catch (Exception $e) {
echo "Caught error: " . $e->message() . "\n";
}
}
}
}
final function addSubEvent($observer)
{
$this->SubEvent[] = $observer;
}
}
class Cat extends Subject
{
public function Cry()
{
echo "Cat crying...\n";
$this->FireAway();
}
}
abstract class Observer
{
public function __construct($sub)
{
$sub->addSubEvent($this);
}
abstract function Response();
}
class Mouse extends Observer
{
private $name;
public function __construct($name, $sub)
{
parent::__construct($sub);
$this->name = $name;
}
public function Response()
{
echo $this->name . " is runing away!\n";
}
}
class Master extends Observer
{
public function __construct($sub)
{
parent::__construct($sub);
}
public function Response()
{
echo "Master is comming!\n";
}
}
// 驱动类
class Program
{
final function main()
{
$cat = new Cat;
$mouse1 = new Mouse("Mouse1", $cat);
$mouse2 = new Mouse("Mouse2", $cat);
$master = new Master($cat);
$cat->Cry();
}
}
$p = new Program;
$p->main();
?>
[/PHP] |
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有帐号?注册
x
|