• B10:迭代器模式 Iterator


    提供了一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示.

    适用场景:
    当你需要访问一个聚合对象,而这个对象不论是什么,你都需要遍历的时候,就用迭代器.

    UML:

    示例代码:

    class User
    {
        private $name,$regTime,$money;
     
        public function __construct($name, $regTime)
        {
            $this->name = $name;
            $this->regTime = $regTime;
        }
     
        public function setMoney($money)
        {
            $this->money = $money;
        }
     
        public function __toString()
        {
            return "{$this->name} :  {$this->regTime} :  {$this->money}";
        }
    }
     
    class UserIterator implements Iterator
    {
        private $users = array();
        private $valid = false;
     
        public function __construct()
        {
            try{
                $sql = "SELECT * FROM yx_users";
                $pdo = new PDO('mysql:host=localhost;dbname=db_zuiyouxin', 'root', 'root');
                $res = $pdo->query($sql);
     
                foreach ($res as $row) {
                    $user = new User($row['name'], $row['created_at']);
                    $user->setMoney($row['money']);
                    $this->users[$row['id']] = $user;
                }
     
                $pdo = null;
            } catch (Exception $e) {
                die('Error:' . $e->getMessage());
            }
        }
     
        public function current()
        {
            return current($this->users);
        }
     
        public function next()
        {
            $this->valid = (next($this->users) === false) ? false : true;
        }
     
        public function key()
        {
            return key($this->users);
        }
     
        public function valid()
        {
            return $this->valid;
        }
     
        public function rewind()
        {
            $this->valid = (reset($this->users) === false) ? false : true;
        }
     
    }
     
    $users = new UserIterator();
     
    foreach ($users as $key => $val) {
        echo $key;
        echo $val;
        echo "<br>";
    }
    

      

  • 相关阅读:
    windows下端口映射(端口转发)
    SQLServer 2008 复制同步(发布、订阅)的几个问题
    SqlServer:此数据库处于单用户模式,导致数据库无法删除的处理
    jQuery函数的等价原生函数【转载】
    JavaScript学习第三天
    持续集成工具hudson【转载】
    linux-unzip命令【转载】
    javascript学习第一天
    java.util.Properties
    Eclipse快捷键【转载】
  • 原文地址:https://www.cnblogs.com/itfenqing/p/7791722.html
Copyright © 2020-2023  润新知