Iterator Behavioural Design Pattern

Posted By : Mohit Jain | 24-Jun-2018

According to Gangs of Four,"The Iterator Pattern gives a way to access the elements of aggregate objects without exposing its underlying representation". 

Remember:- There are lots of ways to put objects into a Collection.Each one have its own pros and cons:-

                            Example:- 1.) In an "Array".

                                              2.) In a "Stack".

                                              3.) In a "List".

 

 " But at some point your client is going to want to iterate over those objects, and when he does, are you going to show him your implementation? We certainly hope  not!That just wouldn’t be professional. Well, you don’t have to risk your career; you’re going to see how you can allow your clients to iterate through  your  objects without ever getting a peek at how you store your objects".

 

Note:- When we say COLLECTION we just mean a group of objects.They might be stored in different data structures like Array,List,Hashtables, but still they represents     COLLECTION.We sometimes call these "Aggregates".

 

Now we have 4 players for this Design pattern:-

1.)Aggregate (an interface):- For the creation of "Iterator" Object.

2.)ConcreteAggregate(an imlementation of Aggregate):- Returns instance of concrete iterator.

3.)Iterator(an Interface):-For access and traversal of Elements in a collection.

4.)ConcreteIterator(an implementation of Iterator):-Maintaining and Keeping  track of current position in the traversal of the aggregate(COLLECTION).

 

Now see how it works in JAVA?

Java provides an implementation of this pattern "Iterator" which provides next() and hasNext() methods.Creation of "Iterator" object is done by a method named iterator().

Example:-

// "List" (interface) is our Aggregate here, having iterator() mehod for creating object of "SomePreImplementedConcreteIterator" class which implements "Iterator" interface

// "ArrayList" is our ConcreteImplementationOfList( here Aggregate is  "List" interface )

// Here iterator() method returns the object of that "SomePreImplementedConcreteIterator"(Preimplemented class) of Iterator(interface) thatswhy not visible in our code here but internally this happens.

//------- code -----------//

List<String> list=new ArrayList<String>();

    Iterator it=list.iterator();

        while(it.hasNext())

        {

        String s=it.next();

        System.out.println("Output :-  "+s);

        }

About Author

Author Image
Mohit Jain

Mohit Jain working as backend java developer having knowlege of core java,spring,hibernate.

Request for Proposal

Name is required

Comment is required

Sending message..