访问者模式
将算法与其所作用的对象隔离开来
类图
代码
<?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);