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

    代码
    using System;
    using System.Collections;
    using System.Collections.Generic;

    public class Node
    {
        
    public string Name
        {
            
    get;
            
    set;
        }
        
    public Node(string s)
        {
            
    this.Name=s;
        }
    }

    public class NodeCollection
    {
        
    private ArrayList list=new ArrayList();
        
    private int nodeIndex=0;
        
    public void AddNode(Node n)
        {
            list.Add(n);
            nodeIndex
    ++;
        }
        
    public Node GetNode(int i)
        {
            
    return ((Node)list[i]);
        }
        
        
    public int NodeIndex
        {
            
    get
            {
                
    return nodeIndex;
            }
        }
    }

    public abstract class Iterator
    {
        
    public abstract  Node Next();
    }
    public class ReverseIterator:Iterator
    {
        
    private NodeCollection nodeCollection;
        
    private int currentIndex;
        
        
    public ReverseIterator(NodeCollection c)
        {
            
    this.nodeCollection=c;
            currentIndex
    =c.NodeIndex-1;
        }
        
        
    public override Node Next()
        {
            
    if(currentIndex==-1)
            {
                
    return null;
            }
            
    else
            {
                
    return (nodeCollection.GetNode(currentIndex--));
            }
        }
    }


    public class MyClass
    {
        
    public static void Main()
        {
            NodeCollection c
    =new NodeCollection();
            c.AddNode(
    new Node("first"));
            c.AddNode(
    new Node("Second"));
            c.AddNode(
    new Node("third"));
            
            ReverseIterator i
    =new ReverseIterator(c);
            Node n;
            
    do
            {
                n
    =i.Next();
                
    if(n!=null)
                {
                    Console.WriteLine(
    "{0}",n.Name);
                }
            }
            
    while(n!=null);
        }
    }
    名称 Iterator
    结构  
    意图 提供一种方法顺序访问一个聚合对象中各个元素, 而又不需暴露该对象的内部表示。
    适用性
    • 访问一个聚合对象的内容而无需暴露它的内部表示。
    • 支持对聚合对象的多种遍历。
    • 为遍历不同的聚合结构提供一个统一的接口(即, 支持多态迭代)。
  • 相关阅读:
    iOS开发之使用 infer静态代码扫描工具
    iOS 组件化开发之使用CocoaPod制作自己的远程私有库
    WKWebView 使用的坑
    iOS 自动化打包发布(Fastlane+ Jenkins+蒲公英)
    Flutter 开发入门实践
    【读书笔记】--《编写高质量iOS与OS X代码的52个有效方法》
    iOS 10.3+ 动态修改 App 图标
    ubuntu16.04 安装 caffe cuda 相关流程
    ubuntu 休眠后窗口边缘出现花边的解决方案
    c++实现二叉树的非递归创建以及非递归先序、中序、后序遍历
  • 原文地址:https://www.cnblogs.com/mikechang/p/1724113.html
Copyright © 2011-2022 走看看