2009年11月1日

PHPでデザインパターン:Iterator(イテレータ)

Filed under: デザインパターン — admin @ 11:19 PM

Student.php

class Student
{
    private $name;
    private $age;
    private $sex;
    public function __construct($name, $age, $sex)
    {
        $this->name = $name;
        $this->age  = $age;
        $this->sex  = $sex;
    }
    public function getName()
    {
        return $this->name;
    }
    public function getAge()
    {
        return $this->age;
    }
    public function getSex()
    {
        return $this->sex;
    }
}

Students.php

class Students iplements IteratorAggregate
{
    private $students;
    public function __construct()
    {
        $this->students = new ArrayObject();
    }
    public function add(Student $student)
    {
        $this->students[] = $student;
    }
    public function getIterator()
    {
        return $this->students->getIterator();
    }
}

MaleIterator.php

require_once 'Student.php';

class MaleIterator extends FileterIterator
{
    public function __construct($iterator)
    {
        parent::__construct($iterator);
    }
    public function accept()
    {
        $student = $this->current();
        return ($student->getSex() === 'male');
    }
}

■クライアントコード

require_once 'Student.php';
require_once 'Students.php';
require_once 'MaleIterator.php';

$students = new Students();
$students->add(new Student('John', 12, 'male'));
$students->add(new Student('Jack', 13, 'male'));
$students->add(new Student('Emily', 14, 'female'));

$iterator = $students->getIterator();
while($iterator->valid()){
    $student = $iterator->current();
    $list[] = array(
        'name' => $student->getName(),
        'age'  => $student->getAge(),
        'sex'  => $student->getSex()
    );
    $student = $iterator->next();
}
var_dump($list);
/*
array(3) {
  [0]=>
  array(3) {
    ["name"]=>
    string(4) "John"
    ["age"]=>
    int(12)
    ["sex"]=>
    string(4) "male"
  }
  [1]=>
  array(3) {
    ["name"]=>
    string(4) "Jack"
    ["age"]=>
    int(13)
    ["sex"]=>
    string(4) "male"
  }
  [2]=>
  array(3) {
    ["name"]=>
    string(5) "Emily"
    ["age"]=>
    int(14)
    ["sex"]=>
    string(6) "female"
  }
}
*/
$iterator = new MaleIterator($iterator);
foreach($iterator as $student){
    $list[] = array(
        'name' => $student->getName(),
        'age'  => $student->getAge(),
        'sex'  => $student->getSex()
    );
}
var_dump($list);
/*
array(2) {
  [0]=>
  array(3) {
    ["name"]=>
    string(4) "John"
    ["age"]=>
    int(12)
    ["sex"]=>
    string(4) "male"
  }
  [1]=>
  array(3) {
    ["name"]=>
    string(4) "Jack"
    ["age"]=>
    int(13)
    ["sex"]=>
    string(4) "male"
  }
}
*/

きれいだ。

コメントはまだありません »

コメントはまだありません。

この投稿へのコメントの RSS フィード。 TrackBack URL

コメントする