关于C# 设计模式 Iterator 迭代器模式

关于C# 设计模式 Iterator 迭代器模式

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

///Iterator(迭代器)模式又称Cursor(游标)模式,用于提供一种方法顺序访问一个聚合对象中各个元素, 而又不需暴露该对象的内部表示。
///add by jzh 2007-04-26
namespace DesignPattern
{
    class Node
    {
        private string name;
        public string Name
        {
            get
            {
                return name;
            }
        }
        public Node(string s)
        {
            name = s;
        }
    }

    class NodeCollection
    {
        private ArrayList list = new ArrayList();
        private int nodeMax = 0;

        public void AddNode(Node n)
        {
            list.Add(n);
            nodeMax++;
        }
        public Node GetNode(int i)
        {
            return ((Node)list[i]);
        }

        public int NodeMax
        {
            get
            {
                return nodeMax;
            }
        }
    }

    abstract class Iterator
    {
        abstract public Node Next();
    }

    class ReverseIterator : Iterator
    {
        private NodeCollection nodeCollection;
        private int currentIndex;

        public ReverseIterator(NodeCollection c)
        {
            nodeCollection = c;
            currentIndex = c.NodeMax - 1; // array index starts at 0!
        }

        override public Node Next()
        {
            if (currentIndex == -1)
                return null;
            else
                return (nodeCollection.GetNode(currentIndex--));
        }
    }
    public class Client
    {
        public static void Main(string[] args)
        {
            NodeCollection c = new NodeCollection();
            c.AddNode(new Node("a"));
            c.AddNode(new Node("b"));
            c.AddNode(new Node("c"));

            ReverseIterator i = new ReverseIterator(c);

            Node n;
            do
            {
                n = i.Next();
                if (n != null)
                    Console.WriteLine("{0}", n.Name);
            } while (n != null);

            Console.ReadLine();
        }
    }
}

 

发表回复

您的电子邮箱地址不会被公开。