abstract class Action {//visitor
abstract public function GetManConclusion($person);
abstract public function GetWomanConclusion($person);
}
class Success extends Action {
public function GetManConclusion($person) {
echo get_class($person) . " 背后多半有一个伟大的女人<br/>";//get_class,返回对象的类名
}
public function GetWomanConclusion($person) {
echo get_class($person) . " 背后大多有一个不成功的男人<br/>";
}
}
class Failing extends Action {
public function GetManConclusion($person) {
echo get_class($person) . " 大醉一场<br/>";
}
public function GetWomanConclusion($person) {
echo get_class($person) . "哭的天翻地覆<br/>";
}
}
class Marry extends Action{
public function GetManConclusion($person){
echo get_class($person)."结束了爱情游戏<br/>";
}
public function GetWomanConclusion($person){
echo get_class($person)."找到了归属<br/>";
}
}
abstract class Person {//elements
abstract public function accept($action);
}
class Man extends Person {
public function accept($action) {
$action->GetManConclusion($this);
}
}
class Woman extends Person {
public function accept($action) {
$action->GetWomanConclusion($this);
}
}
class ObjectStructure {
private $_elements = array ();
public function attach($person) {
$this->_elements[] = $person;
}
public function detach($person) {
if ($key = array_search($person, $this->_elements) !== false)
unset ($this->_elements[$key]);//销毁单个数组元素
}
public function accept($action) {
foreach ($this->_elements as $element) {
$element->accept($action);
}
}
}
//
$objOS = new ObjectStructure();
$objOS->attach(new Man());
$objOS->attach(new Woman());
$objCV1 = new Success();
$objCV2 = new Failing();
$objCV3 = new Marry();
$objOS->accept($objCV1);
$objOS->accept($objCV2);
$objOS->accept($objCV3);
输出结果:
Man 背后多半有一个伟大的女人
Woman 背后大多有一个不成功的男人
Man 大醉一场
Woman哭的天翻地覆
Man结束了爱情游戏
Woman找到了归属