PHP Design Pattern Visitor Visitor Pattern_PHP Tutorial

WBOY
Release: 2016-07-21 15:27:33
Original
800 people have browsed it

复制代码 代码如下:

/**
* Visitor pattern
*
* Represents an operation that acts on each element in an object structure. You can define new operations that act on these elements without changing the class of each element
*
*/
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
";
}
public function visitCroncreteElementB($element)
{
echo get_class($element)." visit 1B
";
}
}
class ConcreteVisitor2 extends Visitor
{
public function visitCroncreteElementA($element)
{
echo get_class($element)." visit 2A
";
}
public function visitCroncreteElementB($element)
{
echo get_class($element)." visit 2B
";
}
}
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);

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/323745.htmlTechArticle复制代码 代码如下: ?php /** * 访问者模式 * * 表示一个作用于某对象结构中的各元素的操作,可以在不改变各元素的类的前提下定义作用于这...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!