php设计模式 Visitor 访问者模式
代码如下:
<?php /** * 访问者模式 * * 表示一个作用于某对象结构中的各元素的操作,可以在不改变各元素的类的前提下定义作用于这些元素的新操作 * */ 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->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()); $objCV1 = new ConcreteVisitor1(); $objCV2 = new ConcreteVisitor2(); $objOS->accept($objCV1); $objOS->accept($objCV2);
相关推荐
TingBen 2020-09-16
Kakoola 2020-01-12
Clevebaby 2012-04-23
New丶Elements 2019-06-27
AHRL 2011-02-17
守望丶 2011-01-19
Backwardelements 2010-12-18
guojing 2010-01-27
lujingjing 2016-05-03
fancyler 2018-02-05
thousfeet 2015-07-23
shonmark 2016-11-18
githubphpnobug 2019-04-17
PHP100 2019-03-28
vczh的日常 2018-04-21
前端外刊评论 2018-03-05
MATLAB 2017-11-28