本文實例講述了PHP基于SPL實現(xiàn)的迭代器模式。分享給大家供大家參考,具體如下:
現(xiàn)在有這么兩個類,Department部門類、Employee員工類:
//部門類class Department{ private $_name; private $_employees; function __construct($name){ $this->_name = $name; $this->employees = array(); } function addEmployee(Employee $e){ $this->_employees[] = $e; echo "員工{$e->getName()}被分配到{$this->_name}中去"; }}//員工類class Employee{ private $_name; function __construct($name){ $this->_name = $name; } function getName(){ return $this->_name; }}//應(yīng)用:$lsgo = new Department('LSGO實驗室');$e1 = new Employee("小錦");$e2 = new Employee("小豬");$lsgo->addEmployee($e1);$lsgo->addEmployee($e2);好了,現(xiàn)在LSGO實驗室已經(jīng)有兩個部員了,現(xiàn)在我想把全部的部員都列出來,就是用循環(huán)來獲取部門的每個員工的詳情。
在這里我們用PHP中的SPL標(biāo)準(zhǔn)庫提供的迭代器來實現(xiàn)。
《大話設(shè)計模式》中如是說:
迭代器模式:迭代器模式是遍歷集合的成熟模式,迭代器模式的關(guān)鍵是將遍歷集合的任務(wù)交給一個叫做迭代器的對象,它的工作時遍歷并選擇序列中的對象,而客戶端程序員不必知道或關(guān)心該集合序列底層的結(jié)構(gòu)。
迭代器模式的作用簡而言之:是使所有復(fù)雜數(shù)據(jù)結(jié)構(gòu)的組件都可以使用循環(huán)來訪問
假如我們的對象要實現(xiàn)迭代,我們使這個類實現(xiàn) Iterator(SPL標(biāo)準(zhǔn)庫提供),這是一個迭代器接口,為了實現(xiàn)該接口,我們必須實現(xiàn)以下方法:
current(),該函數(shù)返回當(dāng)前數(shù)據(jù)項
key(),該函數(shù)返回當(dāng)前數(shù)據(jù)項的鍵或者該項在列表中的位置
next(),該函數(shù)使數(shù)據(jù)項的鍵或者位置前移
rewind(),該函數(shù)重置鍵值或者位置
valid(),該函數(shù)返回 bool 值,表明當(dāng)前鍵或者位置是否指向數(shù)據(jù)值
實現(xiàn)了 Iterator 接口和規(guī)定的方法后,PHP就能夠知道該類類型的對象需要迭代。
我們使用這種方式重構(gòu) Department 類:
class Department implements Iterator{ private $_name; private $_employees; private $_position;//標(biāo)志當(dāng)前數(shù)組指針位置 function __construct($name) { $this->_name = $name; $this->employees = array(); $this->_position = 0; } function addEmployee(Employee $e) { $this->_employees[] = $e; echo "員工{$e->getName()}被分配到{$this->_name}中去"; } //實現(xiàn) Iterator 接口要求實現(xiàn)的方法 function current() { return $this->_employees[$this->_position]; } function key() { return $this->_position; } function next() { $this->_position++; } function rewind() { $this->_position = 0; } function valid() { return isset($this->_employees[$this->_position]); }}//Employee 類同前//應(yīng)用:$lsgo = new Department('LSGO實驗室');$e1 = new Employee("小錦");$e2 = new Employee("小豬");$lsgo->addEmployee($e1);$lsgo->addEmployee($e2);echo "LSGO實驗室部員情況:";//這里其實遍歷的$_employeeforeach($lsgo as $val){ echo "部員{$val->getName()}";}附加:
假如現(xiàn)在我們想要知道該部門有幾個員工,如果是數(shù)組的話,一個 count() 函數(shù)就 ok 了,那么我們能不能像上面那樣把對象當(dāng)作數(shù)組來處理?SPL標(biāo)準(zhǔn)庫中提供了 Countable 接口供我們使用:
class Department implements Iterator,Countable{ //前面同上 //實現(xiàn)Countable中要求實現(xiàn)的方法 function count(){ return count($this->_employees); }}//應(yīng)用:echo "員工數(shù)量:";echo count($lsgo);希望本文所述對大家PHP程序設(shè)計有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選