zoukankan      html  css  js  c++  java
  • 迭代器模式

    定义:在不需要了解内部实现的前提下,遍历一个聚合对象的内部元素
    好处:相比于传统的编程模式,迭代器模式可以隐藏遍历元素的所需的操作

    $users = new IMoocAllUser();
    foreach ($users as $user)
    {
    var_dump($user);
    }

    <?php
    namespace IMooc;

    class AllUser implements Iterator
    {
    protected $ids;
    protected $data = array();
    protected $index;

    function __construct()
    {
    $db = new IMoocDatabaseMySQLi();
    $db->connect('127.0.0.1', 'root', 'root','test');
    $result = $db->query("select id from user");
    $this->ids = $result->fetch_all(MYSQLI_ASSOC);
    }
    //返回当前的数据
    function current()
    {
    $id = $this->ids[$this->index]['id'];
    return Factory::getUser($id);
    }

    //将索引值向下移动
    function next()
    {
    $this->index ++;
    }

    //查询当前是否有数据
    function valid()
    {
    return $this->index < count($this->ids);
    }

    //将迭代器移动到集合的开头
    function rewind()
    {
    $this->index = 0;
    }

    //返回当前key
    function key()
    {
    return $this->index;
    }
    }

    <?php
    namespace IMooc;

    class Factory
    {
    static function getUser($id)
    {
    $key = 'user_'.$id;
    $user = Register::get($key);
    if (!$user)
    {
    $user = new User($id);
    Register::set($key, $user);
    }
    return $user;
    }
    }




  • 相关阅读:
    CCF NOI1079 合法C标识符
    CCF NOI1080 统计字符
    CCF NOI1076 进制转换
    CCF NOI1065 最小公倍数
    CCF NOI1139 高精度减法
    CCF NOI1138 高精度加法
    CCF NOI1115 找数
    CCF NOI1097 数列
    CCF NOI1089 高精度运算
    NUC1931 Problem D 区间素数【素数筛选】
  • 原文地址:https://www.cnblogs.com/phonecom/p/cc5902329c5cee3164670b128291264f.html
Copyright © 2011-2022 走看看