Learn PHP Design Patterns PHP Implementation Visitor pattern (Visitor) _php tips

Source: Internet
Author: User
Tags learn php

The visitor pattern represents an operation that acts on each element in an object structure. It can define new operations that function on these elements without modifying the individual element classes, that is, dynamically increasing the specific audience role.
The visitor pattern utilizes dual allocation. The visitor passes in the accept method of the Element object, and then the element object passes itself in to the visitor, after which the visitor executes the corresponding method of the element.
The visitor pattern is more used in the case of a diverse aggregation type. In ordinary form, it is necessary to determine what type each element belongs to and then do the appropriate operation, resulting in a lengthy conditional transfer statement. And the visitor pattern can solve this problem better. Call $element->accept ($vistor) uniformly for each element.
When the visitor pattern is more stable than the class structure being accessed, the subclass is not added casually. The visitor pattern allows the access structure to add new methods.
The visitor pattern actually separates the elements in the object structure and acts on them, so that we do not need to use the IF statement to determine the method invocation based on the elements in the object structure, that is, to encapsulate the operation.
However, if you add a new element node, it can result in changes that include the visitor interface and its subclasses, which violates the open and closed principle in object-oriented.
When this happens, it generally means that the visitor pattern may no longer be applicable, or that there is a problem with the design!
First, visitor pattern structure diagram

Second, the main role in the visitor model

1) Abstract visitor Role (Visitor): provides an access operator interface for each concrete element in the object structure (objectstructure). The name and parameters of the operation interface identify the specific element role to be accessed. This allows the visitor to access it directly through the specific interface of the element role.
2) Specific visitor Role (Concretevisitor): implements actions that are declared for individual element roles in the abstract visitor role interface.
3) Abstract node (node) role: This interface defines a accept operation to accept a specific visitor.
4) Specific node role: implements accept operations in the abstract node role.
5) Object structure role (objectstructure): This is a necessary role to use the visitor pattern. It has the following characteristics: it can enumerate its elements; it can provide a high-level interface to allow the visitor to access its elements; it can be a composite (combination pattern) or a collection, such as a list or a unordered set (in PHP we use an array instead, Because an array in PHP is inherently a collection of data of any type, the
three, the advantages and disadvantages of the visitor pattern
Visitor mode have the following benefits : the
1) visitor pattern makes it easy to add new operations. Using the visitor pattern allows you to add new actions without modifying the specific element classes. It is mainly through the accept method of the element class to accept a new visitor object to implement. If some operations depend on a complex structure object, it is generally more complicated to add new operations. With the visitor pattern, adding new operations means adding a new visitor class, so it becomes easy. The
2) visitor pattern centralizes the behavior in a visitor object, rather than spreading it into a single node class. The
3) visitor pattern accesses the member classes belonging to different hierarchy structures by crossing the hierarchy of several classes. Iterations can only access member objects that belong to the same type hierarchy, not objects that belong to different hierarchical structures. Visitor mode can do this.
4) Accumulation status. Each individual visitor object concentrates on the associated behavior, thus allowing the state of the execution to accumulate within itself rather than being dispersed into many node objects during the access process. This is beneficial to system maintenance.

The visitor pattern has the following drawbacks :
1 it becomes difficult to add new node classes. Each additional new node means adding a new abstraction to the abstract visitor role and adding the appropriate actions to each specific audience class.
2) Damage encapsulation. The visitor pattern requires that the visitor object access and invoke the operations of each node object, implying a requirement for all node objects: they must expose some of their own operations and internal state. Otherwise, the visitor's visit becomes meaningless. Because the accessors themselves accumulate the state required for the access operation so that these states are no longer stored in the node object, this is also a breach of encapsulation.

The premise of using the visitor pattern is that the object types in the object group structure (Collection) rarely change.
In interface visitor and element, make sure that the element rarely changes, that is to say, make sure that the new element element type is not added frequently, and that you can change the behavior or operation of the visitor, that is, the different subclasses of visitor can have multiple, This is the most convenient way to use the visitor pattern.
If the collection of objects in the collection of objects often changes, not only does the visitor implementation change, Concretevisitor also increases the corresponding behavior, Gof suggests that it is better to define actions individually in these object classes without using the visitor design pattern.

Iv. Visitor mode and other modes

1. If the structure object being browsed is linear, it is possible to use an iterative mode instead of a visitor pattern
2, visitor mode to browse some of the structural objects of the composite mode
Above two points from the Java and schema book

Five, Visitor mode PHP sample

<?php interface Visitor {public function Visitconcreteelementa (Concreteelementa $elementA);
Public Function Visitconcreteelementb (CONCRETEELEMENTB $elementB);
} interface Element {Public function accept (Visitor $visitor);} /** * Specific Visitor 1/class ConcreteVisitor1 implements Visitor {public Function Visitconcreteelementa (Concreteelementa $el Ementa) {echo $elementA->getname ().
 "Visitd by ConcerteVisitor1 <br/>"; The Public Function visitconcreteelementb (Concreteelementb $elementB) {echo $elementB->getname ().
 "Visited by ConcerteVisitor1 <br/>"; }/** * Specific visitor 2/class ConcreteVisitor2 implements Visitor {public Function Visitconcreteelementa (Concreteelem Enta $elementA) {echo $elementA->getname ().
 "Visitd by ConcerteVisitor2 <br/>"; The Public Function visitconcreteelementb (Concreteelementb $elementB) {echo $elementB->getname ().
 "Visited by ConcerteVisitor2 <br/>"; }/** * Specific element A/class CoNcreteelementa implements Element {private $_name;
 Public function __construct ($name) {$this->_name = $name;
 The Public Function GetName () {return $this->_name; /** * Accepts a new method that the visitor calls to it for the element * @param Visitor $visitor/Public Function accept (Visitor $visitor) {$visitor->vis
 Itconcreteelementa ($this);
 }/** * Specific element b * * * class CONCRETEELEMENTB implements element {private $_name;
 Public function __construct ($name) {$this->_name = $name;
 The Public Function GetName () {return $this->_name; /** * Accepts a new method that the visitor calls to it for the element * @param Visitor $visitor/Public Function accept (Visitor $visitor) {$visitor->vis
 }/** * Object structure is the set of elements/class Objectstructure {private $_collection;
 Public Function __construct () {$this->_collection = array ();
 The Public function attach (Element $element) {return Array_push ($this->_collection, $element); The Public function detach (Element $element) {$index = Array_search ($element, $this->_collection);
 if ($index!== FALSE) {unset ($this->_collection[$index]);
 return $index; The public function accept (Visitor $visitor) {foreach ($this->_collection as $element) {$element->accept ($visit
 }} class Client {/** * Main program.
 * * public static function main () {$elementA = new Concreteelementa ("Elementa");
 $elementB = new Concreteelementb ("Elementb");
 $elementA 2 = new Concreteelementb ("ElementA2");
 $visitor 1 = new ConcreteVisitor1 ();
 $visitor 2 = new ConcreteVisitor2 ();
 $os = new Objectstructure ();
 $os->attach ($elementA);
 $os->attach ($elementB);
 $os->attach ($elementA 2);
 $os->detach ($elementA);
 $os->accept ($visitor 1);
 $os->accept ($visitor 2); } client::main ();?>

The above is the use of PHP to implement the visitor pattern of the code, there are some of the concept of visitor patterns to distinguish between the hope that the study has helped.

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.