访问者模式

将算法与其所作用的对象隔离开来

类图

2024072913592008.png

代码

<?php
 
// 访问者接口
interface Visitor
{
public function visitConcreteElementA(ConcreteElementA $element): void;
public function visitConcreteElementB(ConcreteElementB $element): void;
}
 
// 具体访问者类
class ConcreteVisitor1 implements Visitor
{
public function visitConcreteElementA(ConcreteElementA $element): void
{
echo "ConcreteVisitor1: " . $element->operationA() . "\n";
}
 
public function visitConcreteElementB(ConcreteElementB $element): void
{
echo "ConcreteVisitor1: " . $element->operationB() . "\n";
}
}
 
class ConcreteVisitor2 implements Visitor
{
public function visitConcreteElementA(ConcreteElementA $element): void
{
echo "ConcreteVisitor2: " . $element->operationA() . "\n";
}
 
public function visitConcreteElementB(ConcreteElementB $element): void
{
echo "ConcreteVisitor2: " . $element->operationB() . "\n";
}
}
 
 
// 访问者接口
interface Visitor
{
public function visitConcreteElementA(ConcreteElementA $element): void;
public function visitConcreteElementB(ConcreteElementB $element): void;
}
 
// 具体访问者类
class ConcreteVisitor1 implements Visitor
{
public function visitConcreteElementA(ConcreteElementA $element): void
{
echo "ConcreteVisitor1: " . $element->operationA() . "\n";
}
 
public function visitConcreteElementB(ConcreteElementB $element): void
{
echo "ConcreteVisitor1: " . $element->operationB() . "\n";
}
}
 
class ConcreteVisitor2 implements Visitor
{
public function visitConcreteElementA(ConcreteElementA $element): void
{
echo "ConcreteVisitor2: " . $element->operationA() . "\n";
}
 
public function visitConcreteElementB(ConcreteElementB $element): void
{
echo "ConcreteVisitor2: " . $element->operationB() . "\n";
}
}
 
function clientCode(array $elements, Visitor $visitor)
{
foreach ($elements as $element) {
$element->accept($visitor);
}
}
 
// 创建元素对象
$elements = [
new ConcreteElementA(),
new ConcreteElementB()
];
 
// 使用ConcreteVisitor1访问元素
echo "Using ConcreteVisitor1:\n";
$visitor1 = new ConcreteVisitor1();
clientCode($elements, $visitor1);
 
// 使用ConcreteVisitor2访问元素
echo "\nUsing ConcreteVisitor2:\n";
$visitor2 = new ConcreteVisitor2();
clientCode($elements, $visitor2);