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();
    }
  • 相关阅读:
    poj3984 迷宫问题(简单搜索+记录路径)
    substr
    poj3087 Shuffle'm Up
    学生管理系统
    win10配置gcc编译环境
    poj3278 Catch That Cow
    将字符串str1复制为字符串str2的三种解决方法
    poj2251 Dungeon Master
    cf 410
    7.20 Codeforces Beta Round #8
  • 原文地址:https://www.cnblogs.com/shineqiujuan/p/1704919.html
Copyright © 2011-2022 走看看