PHP design mode Visitor Visitor mode

Source: Internet
Author: User

Copy CodeThe code is as follows:
<?php
/**
* Visitor Mode
*
* represents an operation that acts on elements in an object structure, and can define new actions that affect 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<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-&GT;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 ());
$objCV 1 = new ConcreteVisitor1 ();
$objCV 2 = new ConcreteVisitor2 ();
$objOS->accept ($objCV 1);
$objOS->accept ($objCV 2);



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.