zoukankan      html  css  js  c++  java
  • 迭代器模式【大话设计模式DEMO】

    代码
    abstract class Iterator
    {
    public abstract object First();
    public abstract object Next();
    public abstract bool IsDone();
    public abstract object CurrentItem();
    }

    abstract class Aggregate
    {
    public abstract Iterator CreateIterator();
    }

    class ConcreteIterator : Iterator
    {
    private ConcreteAggregate aggregate;
    private int current = 0;
    public ConcreteIterator(ConcreteAggregate agg)
    {
    this.aggregate = agg;
    }
    public override object First()
    {
    return this.aggregate[0];
    }

    public override object Next()
    {
    object ret = null;
    current
    ++;
    if (current < aggregate.Count)
    ret
    = aggregate[current];
    return ret;
    }

    public override bool IsDone()
    {
    return current > aggregate.Count ? true : false;
    }

    public override object CurrentItem()
    {
    return this.aggregate[current];
    }
    }

    class ConcreteAggregate : Aggregate
    {
    private IList<object> items = new List<object>();

    public override Iterator CreateIterator()
    {
    return new ConcreteIterator(this);
    }

    public int Count
    {
    get { return items.Count; }
    }

    public object this[int index]
    {
    get { return items[index]; }
    set { items.Insert(index, value); }
    }
    }
    代码
    static void Main()
    {
    ConcreteAggregate a
    = new ConcreteAggregate();
    a[
    0] = "a";
    a[
    1] = "b";
    a[
    2] = "c";
    a[
    3] = "d";
    a[
    4] = "e";
    a[
    5] = "f";
    Iterator i
    = new ConcreteIterator(a);
    object item = i.First();
    while(!i.IsDone())
    {
    Console.WriteLine(i.CurrentItem());
    i.Next();
    }
    Console.Read();
    }
  • 相关阅读:
    不务正业系列-浅谈《过气堡垒》,一个RTS玩家的视角
    [LeetCode] 54. Spiral Matrix
    [LeetCode] 40. Combination Sum II
    138. Copy List with Random Pointer
    310. Minimum Height Trees
    4. Median of Two Sorted Arrays
    153. Find Minimum in Rotated Sorted Array
    33. Search in Rotated Sorted Array
    35. Search Insert Position
    278. First Bad Version
  • 原文地址:https://www.cnblogs.com/shineqiujuan/p/1704919.html
Copyright © 2011-2022 走看看