標籤:blog http io ar os for 資料 div on
<?php /** * 訪問者模式 * 封裝某些作用於某種資料結構中各元素的操作,它可以在不改變資料結構的前提下定義作用於這些元素的新的操作。 * 行為類模式 */ /**抽象訪問者:抽象類別或者介面,聲明訪問者可以訪問哪些元素,具體到程式中就是visit方法中的參數定義哪些對象是可以被訪問的。訪問者:實現抽象訪問者所聲明的方法,它影響到訪問者訪問到一個類後該幹什麼,要做什麼事情。抽象元素類:介面或者抽象類別,聲明接受哪一類訪問者訪問,程式上是通過accept方法中的參數來定義的。抽象元素一般有兩類方法,一部分是本身的商務邏輯,另外就是允許接收哪類訪問者來訪問。元素類:實現抽象元素類所聲明的accept方法,通常都是visitor.visit(this),基本上已經形成一種定式了。結構對象:一個元素的容器,一般包含一個容納多個不同類、不同介面的容器,如List、Set、Map等,在項目中一般很少抽象出這個角色。 */ interface Visitor { public function visitConcreteElementA(ConcreteElementA $elementA); public function visitConcreteElementB(concreteElementB $elementB); } interface Element { public function accept(Visitor $visitor); } /** * 具體的訪問者1 */ class ConcreteVisitor1 implements Visitor { public function visitConcreteElementA(ConcreteElementA $elementA){ echo $elementA->getName(),‘ visitd by ConcerteVisitor1 <br />‘; } public function visitConcreteElementB(ConcreteElementB $elementB){ echo $elementB->getName().‘ visited by ConcerteVisitor1 <br />‘; } } /** * 具體的訪問者2 */ class ConcreteVisitor2 implements Visitor { public function visitConcreteElementA(ConcreteElementA $elementA){ echo $elementA->getName(), ‘ visitd by ConcerteVisitor2 <br />‘; } public function visitConcreteElementB(ConcreteElementB $elementB){ echo $elementB->getName(), ‘ visited by ConcerteVisitor2 <br />‘; } } /** * 具體元素A */ class ConcreteElementA implements Element { private$_name; public function __construct($name){ $this->_name =$name; } public function getName(){ return$this->_name; } /** * 接受訪問者調用它針對該元素的新方法 * @param Visitor $visitor */ public function accept(Visitor $visitor){ $visitor->visitConcreteElementA($this); } } /** * 具體元素B */ class ConcreteElementB implements Element { private$_name; public function __construct($name){ $this->_name =$name; } public function getName(){ return$this->_name; } /** * 接受訪問者調用它針對該元素的新方法 * @param Visitor $visitor */ public function accept(Visitor $visitor){ $visitor->visitConcreteElementB($this); } } /** * 對象結構 即元素的集合 */ class ObjectStructure { private$_collection; public function __construct(){ $this->_collection =array(); } public function attach(Element $element){ return array_push($this->_collection,$element); } public function detach(Element $element){ $index=array_search($element,$this->_collection); if($index!==FALSE){ unset($this->_collection[$index]); } return$index; } public function accept(Visitor $visitor){ foreach($this->_collection as $element){ $element->accept($visitor); } } } class Client { /** * Main program. */ public static function main(){ $elementA = new ConcreteElementA("ElementA"); $elementB = new ConcreteElementB("ElementB"); $elementA2 = new ConcreteElementB("ElementA2"); $visitor1 = new ConcreteVisitor1(); $visitor2 = new ConcreteVisitor2(); $os = new ObjectStructure(); $os->attach($elementA); $os->attach($elementB); $os->attach($elementA2); $os->detach($elementA); $os->accept($visitor1); $os->accept($visitor2); } } Client::main(); ?>
UML類圖如下
php實現設計模式之 訪問者模式