码迷,mamicode.com
首页 > 其他好文 > 详细

23种设计模式之迭代器模式(Iterator)

时间:2017-04-10 17:03:09      阅读:246      评论:0      收藏:0      [点我收藏+]

标签:initial   csdn   fit   reg   obj   ext   etl   object   设计   

迭代器模式是一种对象的行为型模式,提供了一种方法来访问聚合对象,而不用暴露这个对象的内部表示。迭代器模式支持以不同的方式遍历一个聚合对象,复杂的聚合可用多种方法来进行遍历;允许在同一个聚合上可以有多个遍历,每个迭代器保持它自己的遍历状态,因此,可以同时进行多个遍历操作。

优点:

1)支持集合的不同遍历。

2)简化了集合的接口。

使用场景:

1)在不开发集合对象内部表示的前提下,访问集合对象内容。

2)支持集合对象的多重遍历。

3)为遍历集合中的不同结构提供了统一的接口。

技术分享

Iterator 模式

public interface Aggregate  
{  
    Iterator iterator();  
}  
public class Book  
{  
    public Book()  
    {  
        //  
    }  
  
    public string GetName()  
    {  
        return "这是一本书";  
    }  
} 
public class BookShelf  
{  
    private IList<Book> books;  
    public BookShelf(int initialsize)  
    {  
        this.books = new List<Book>(initialsize);  
    }  
  
    public Book GetBookAt(int index)  
    {  
        return books[index] as Book;  
    }  
  
    public int GetLength()  
    {  
        return books.Count;  
    }  
  
    public Iterator iterator()  
    {  
        return new BookShelfIterator(this);  
    }  
}  
public class BookShelfIterator : Iterator  
{  
    private BookShelf bookShelf;  
    private int index;  
    public BookShelfIterator(BookShelf bookShelf)  
    {  
        this.bookShelf = bookShelf;  
        this.index = 0;  
    }  
  
    public bool HasNext()  
    {  
        if (index < bookShelf.GetLength())  
        {  
            return true;  
        }  
        else  
        {  
            return false;  
        }  
    }  
  
    public object Next()  
    {  
        Book book = bookShelf.GetBookAt(index) as Book;  
        index++;  
        return book;  
    }  
}  
public interface Iterator  
{  
    bool HasNext();  
    Object Next();  
}  
class Program  
{  
    static void Main(string[] args)  
    {  
        //迭代器模式  
          BookShelf bookShelf = new BookShelf(4);  
        Iterator.Iterator it = bookShelf.iterator();  
        while (it.HasNext())  
        {  
            Book book = it.Next() as Book;  
            Console.WriteLine("" + book.GetName());  
        }  
    }  
}  

 

23种设计模式之迭代器模式(Iterator)

标签:initial   csdn   fit   reg   obj   ext   etl   object   设计   

原文地址:http://www.cnblogs.com/guwei4037/p/6689449.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!