标题: PHP编程:php设计形式 Visitor 会见者形式 [打印本页] 作者: 爱飞 时间: 2015-2-3 23:37 标题: PHP编程:php设计形式 Visitor 会见者形式 理解动态语言的概念,运做机制,熟悉PHP语法 复制代码 代码以下:
<?php
/**
* 会见者形式
*
* 暗示一个感化于某对象布局中的各元素的操作,可以在不改动各元素的类的条件下界说感化于这些元素的新操作
*
*/
abstract class Visitor
{
abstract public function visitCroncreteElementA($element);
abstract public function visitCroncreteElementB($element);
}
class ConcreteVisitor1 extends Visitor
{
public function visitCroncreteElementA($element)
{
echo get_class($element)." visit 1A<br/>";
}
public function visitCroncreteElementB($element)
{
echo get_class($element)." visit 1B<br/>";
}
}
class ConcreteVisitor2 extends Visitor
{
public function visitCroncreteElementA($element)
{
echo get_class($element)." visit 2A<br/>";
}
public function visitCroncreteElementB($element)
{
echo get_class($element)." visit 2B<br/>";
}
}
abstract class Element
{
abstract public function accept($visitor);
}
class ConcreteElementA extends Element
{
public function accept($visitor)
{
$visitor->visitCroncreteElementA($this);
}
}
class ConcreteElementB extends Element
{
public function accept($visitor)
{
$visitor->visitCroncreteElementB($this);
}
}
class ObjectStructure
{
private $_elements = array();
public function attach($element)
{
$this->_elements[] = $element;
}
public function detach($element)
{
if($key = array_search($element,$this->_elements) !== false) unset($this->_elements[$key]);
}
public function accept($visitor)
{
foreach($this->_elements as $element)
{
$element->accept($visitor);
}
}
}
//
$objOS = new ObjectStructure();
$objOS->attach(new ConcreteElementA());
$objOS->attach(new ConcreteElementB());
$objCV1 = new ConcreteVisitor1();
$objCV2 = new ConcreteVisitor2();
$objOS->accept($objCV1);
$objOS->accept($objCV2);