Friday, 24 November 2017

Design Patterns - Basic Iterator

Among the most common things in a collection of items is the ability to iterate through the collection , in Java for example there are data structures that allowing us to create collections for primitive data or our custom classes.
Here some : ArrayList<T>, LinkedList<T> , HashSet<T> and others...

The above have something in common , all are implementing  the Interfaces : Collection and Iterable.

Below there is a simplified UML diagram  illustrating the ArrayList <T>:

The above relationships are allowing us to use the magic:

for(String s: stringList){
     // do something with s

The above is a convenient way to write a foreach  loop in Java, but the language it self translates it to:

Iterator<String> si = stringList.iterator();

   String s = si.getNext();
   // do something with s

Now armed with this knowledge we can go beyond the default behaviors of the build in collections and can customize it for our own needs!

Basic Iterator Pattern:

Project : CarPartsStore

Here we will illustrate the customized behavior by exploring a Store that sells car parts, in this code-base we have the Warehouse class that contains a List of CarPart .

What we do here: We will use the basic Iterator Pattern to iterate through our Warehouse class for CarPart .

We will make something like the following to work:

for(CarPart part: Warehouse){
  // do interesting stuff ...

by default the above is not working as our warehouse has a field of ArrayList<CarPart> ,  but having the new awesome Iterator powers we can can do it !

 In our Warehouse class we added the implements Iterable :

public class Warehouse implements Iterable<CarPart> 

notice we used the CarPart type , as we want to iterate through a collection of CarPart.

also we have implemented the following :

public Iterator<CarPart> iterator() {
    return carPartList.iterator();

Now when we try to iterate through our warehouse we iterate through the carPartList !
Congratulations ! now you have learned how to take iteration to your hands!

Feel free to experiment with the code!!! 


No comments:

Post a Comment