Advertisement
yakovmonarh

Итератор (iterator)

Aug 31st, 2019
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.57 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Threading;
  5. using System.Linq;
  6. using System.Threading.Tasks;
  7.  
  8. class Program
  9. {
  10.    static void Main(string[] args)
  11.    {
  12.     Library library = new Library();
  13.     Reader reader = new Reader();
  14.     reader.SeeBooks(library);
  15.    
  16.     Console.ReadLine();
  17.    }
  18. }
  19.  
  20. class Reader
  21. {
  22.     public void SeeBooks(Library library)
  23.     {
  24.         IBookIterator iterator = library.CreateNumerator();
  25.         while(iterator.HasNext())
  26.         {
  27.             Book book = iterator.Next();
  28.             Console.WriteLine(book.Name);
  29.         }
  30.     }
  31. }
  32.  
  33. interface IBookIterator
  34. {
  35.     bool HasNext();
  36.     Book Next();
  37. }
  38.  
  39. interface IBookNumerable
  40. {
  41.     IBookIterator CreateNumerator();
  42.     int Count {get;}
  43.     Book this[int index] {get;}
  44. }
  45.  
  46. class Book
  47. {
  48.     public string Name{get;set;}
  49. }
  50.  
  51. class Library : IBookNumerable
  52. {
  53.     private Book[] books;
  54.    
  55.     public Library()
  56.     {
  57.         books = new Book[]
  58.         {
  59.             new Book{Name = "Война и мир"},
  60.             new Book{Name = "Отцы и дети"},
  61.             new Book{Name = "Вишневый сад"}
  62.         };
  63.     }
  64.    
  65.     public int Count
  66.     {
  67.         get{return books.Length;}
  68.     }
  69.    
  70.     public Book this[int index]
  71.     {
  72.         get{return books[index];}
  73.     }
  74.    
  75.     public IBookIterator CreateNumerator()
  76.     {
  77.         return new LibraryNumerator(this);
  78.     }
  79. }
  80.  
  81. class LibraryNumerator : IBookIterator
  82. {
  83.     IBookNumerable aggregate;
  84.     int index = 0;
  85.    
  86.     public LibraryNumerator(IBookNumerable a)
  87.     {
  88.         aggregate = a;
  89.     }
  90.    
  91.     public bool HasNext()
  92.     {
  93.         return index < aggregate.Count;
  94.     }
  95.    
  96.     public Book Next()
  97.     {
  98.         return aggregate[index++];
  99.     }
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement