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. 使用繁琐,对于简单的循环,使用迭代器比较麻烦;
  • 相关阅读:
    【HDU】4092 Nice boat(多校第四场1006) ——线段树 懒惰标记 Prime
    【POJ】2528 Mayor's posters ——离散化+线段树 Prime
    【HDU】1754 I hate it ——线段树 单点更新 区间最值 Prime
    C语言 linux环境基于socket的简易即时通信程序 Prime
    Java异常处理
    重载和重写的区别与联系
    SQL Server的优点与缺点
    Servlet基础
    C语言图形编程
    socket通讯,TCP,UDP,HTTP的区别
  • 原文地址:https://www.cnblogs.com/George1994/p/6037647.html
Copyright © 2011-2022 走看看