-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathVisitor.php
56 lines (46 loc) · 1.27 KB
/
Visitor.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?php
/**
* Visitor design pattern (example of implementation)
*
* @author Enrico Zimuel (enrico@zimuel.it)
* @see http://en.wikipedia.org/wiki/Visitor_pattern
*/
interface Visited {
public function accept(Visitor $visitor);
}
class VisitedArray implements Visited
{
protected $elements = array();
public function addElement($element){
$this->elements[]=$element;
}
public function getSize(){
return count($this->elements);
}
public function accept(Visitor $visitor){
$visitor->visit($this);
}
}
interface Visitor {
public function visit(VisitedArray $elements);
}
class DataVisitor implements Visitor
{
protected $info;
public function visit(VisitedArray $visitedArray){
$this->info = sprintf ("The array has %d elements",
$visitedArray->getSize());
}
public function getInfo(){
return $this->info;
}
}
// Usage example
$visitedArray = new VisitedArray();
$visitedArray->addElement('Element 1');
$visitedArray->addElement('Element 2');
$visitedArray->addElement('Element 3');
$dataVisitor = new DataVisitor();
$visitedArray->accept($dataVisitor);
$dataVisitor->visit($visitedArray);
printf("Info from visitor object: %s\n", $dataVisitor->getInfo());