Definition:
•       Iterator
pattern falls under behavioural pattern category.
•       In
object-oriented programming, the iterator pattern is a design
pattern in which an iterator is used to traverse a container
and access the container's elements.
•       This
pattern is used to get a way to access the elements of a collection object in
sequential manner without any need to know its underlying representation.
•       What
Iterator patterns is NOT? -  repeat task
/ solving solution
Purpose:
•       Easy
access to elements of container. 
•       Avoid
data tampering at client side 
•       Perform
simultaneous Iterators
Why Iterator Pattern (Problem statement): 
•       Consider
an application used to print the details of a bank (its name and its manager
name). For now only 3 banks details are known, and this is how it prints. 
        Display(bank1.BankName);
     Display(bank1.Locatioin);
     Display(bank2.BankName);
     Display(bank2.Location);
•       Let’s
say now 100 bank details are known, now the complexity arises, as the
application will now need to print all the 100 bank details one by one. 
•       To
overcome the above issue, we can use the Iterator pattern.
Implementation:
•       Step 1: Store
all the objects ( all bank details ) in a container (list).
                private
ArrayList m_ArrBank = new ArrayList();
                 m_ArrBank
.Add(new Bank("ABC", “Location1"));
                 m_ArrBank
.Add(new Bank("XYZ", " Location2"));
                 m_ArrBank
.Add(new Bank("TUV", "Location3”)); 
•       Step2: Access
all the elements of the list by using an Iterator ( i.e. by using foreach)
                 foreach
(Bank item in m_ArrBank )  // Iterator
                 {
                      Display(item.Location);
                      Display(item.BankName);
                 }
UML :
Example in C# :
Examples of Iterator :
Template Library Containers implement their iterators
Template Library algorithm are defines in terms iterator
C#
IEnumerable and IEnumurator are used
Java
SDK defines iterator interface
Collections implement their iterators
SQL
Cursor is an iterator.
TV Remote control
Types of Iterator :
•       Internal
Iterator
•       External
Iterator
•       Single
Integral Iterator
•       Multiple
Integral Iterator


 
No comments:
Post a Comment