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

    定义

    提供一种方法访问一个容器对象中各个元素,而又不需要暴露该对象的内部细节;

    行为型模式

    角色

    • 迭代器角色(Iterator):迭代器角色负责定义访问和遍历元素的接口;
    • 具体迭代器角色(Concrete Iterator):具体迭代器角色要实现迭代器接口,并要记录遍历中的当前位置;
    • 容器角色(Container): 容器角色负责提供创建具体迭代器角色的接口;
    • 具体容器角色(Concrete Container): 具体容器角色实现创建具体迭代器角色的接口-这个具体迭代器角色于该容器的结构相关;

    从网上找到的例图
    enter image description here


    适用场景

    • 访问一个容器对象的内容而无关暴露它的内部表示;
    • 支持对容器对象的多种遍历;
    • 为遍历不同的容器结构提供一个统一的接口;

    例子


    实现代码

    /**
     * Created by George on 16/7/6.
     */
    
    // 抽象迭代器
    var Iterator = function () {
        this.next = function () {
            
        };
    
        this.hasNext = function () {
            
        };
    
    };
    
    // 具体迭代器实现迭代器接口
    var ConcreteIterator = function (list) {
        this.list = list;
        this.cursor = 0;
    };
    ConcreteIterator.prototype = new Iterator();
    ConcreteIterator.prototype.hasNext = function () {
        return !(this.cursor == this.list.length);
    };
    ConcreteIterator.prototype.next = function () {
        var obj = null;
        if (this.hasNext()) {
            obj = this.list[this.cursor++];
        }
        return obj;
    };
    
    // 抽象容器
    var Container = function () {
        this.add = function (obj) {
            
        };
        this.remove = function (obj) {
            
        };
        this.iterator = function () {
            
        };
    };
    
    // 具体容器实现容器接口
    var ConcreteContainer = function (list) {
        this.list = list;
    };
    ConcreteContainer.prototype = new Container();
    ConcreteContainer.prototype.add = function (obj) {
        this.list.push(obj);
    };
    ConcreteContainer.prototype.iterator = function () {
        return new ConcreteIterator(this.list);
    };
    ConcreteContainer.prototype.remove = function (obj) {
        this.list.remove(obj);
    };
    
    // 主要实现
    var list = ["a", "b", "c"];
    var container = new ConcreteContainer(list);
    var iterator = container.iterator();
    
    while (iterator.hasNext()) {
        var str = iterator.next().toString();
        console.log(str);
    }
    

    实现结果:

    这里写图片描述


    优缺点

    1. 简化了遍历方式,特别是对于hash表来说;
    2. 提供多种遍历方式;
    3. 封装性良好,用户只需要得到迭代器就可以遍历,对于遍历算法则不关心;

    注意的是

    1. 使用繁琐,对于简单的循环,使用迭代器比较麻烦;
  • 相关阅读:
    大约PCA算法学习总结
    内部硬盘的硬件结构和工作原理进行了详细解释
    DWZ使用注意事项
    cocos2d-x 在XML分析和数据存储
    HTML精确定位:scrollLeft,scrollWidth,clientWidth,offsetWidth完全详细的说明
    hdu 1114 Piggy-Bank
    getResources()方法
    人机博弈-吃跳棋游戏(三)代移动
    Oracle 11g client安装和配置。
    的微信公众号开发 图灵机器人接口允许调用自己的微通道成为一个智能机器人
  • 原文地址:https://www.cnblogs.com/George1994/p/6037647.html
Copyright © 2011-2022 走看看