Sunday, 26 November 2017

Design Patterns - Advanced Iterator

In the Basic Iterator article you have used an existing iterator to simplify our Car Parts Store , having learned about iterators you might have wondered if you can create your own iterator...


Project : CarPartsStore - Advanced


At some point our Car Parts Store has become more sophisticated , at the beginning we had only one List<CarPart> carPartList with all the available parts, but the Warehouse manager also wants to have a log where he/she can keep track of what parts have been sold.

The soldLog is also a List<CarPart> where we have all the parts that we have sold to our customers, things are getting more interesting for our Warehouse class and we need to use the advanced iterator pattern to accommodate our new needs.

As we have done in the basic iterator pattern we will start by making our Warehouse class to implement Iterable :

public class Warehouse implements Iterable<CarPart> 



 and implement :

@Override 
public Iterator<CarPart> iterator() {
     return new WarehouseIterator();
}

WarehouseIterator is not existing right now, this will be our custom iterator !
We will make it a private inner class as it needs access to our Warehouse inner workings, we can name it anything the important things are:
  • it is an inner class
  • implements Iterator<CarPart>
Our inner class will look like:

private class WarehouseIterator implements Iterator<CarPart> {
 
 @Override 
 public boolean hasNext() {
        return false;
    } 
 
 @Override 
 public CarPart next() {
        return null;
    }
}

now it's time to get it done:
 we add the following cursors in our WarehouseIterator class:

 // Here we put our cursors: 
Iterator<CarPart> partsInStockIterator = carPartList.iterator();
Iterator<CarPart> soldPartsIterator = soldLog.iterator();

now we can keep tracking both Lists using their iterators

 
@Override 
 public boolean hasNext() {
    // if any of the iterators have next return it till there is no next 
 return partsInStockIterator.hasNext()|| soldPartsIterator.hasNext();
}

as long either iterator has a next we return it till there are no more.

 
@Override
 public CarPart next() {
    CarPart carPart;
    if(partsInStockIterator.hasNext()){
        System.out.print("Stocked : ");
        carPart = partsInStockIterator.next();
    }else {
        System.out.print("Sold : ");
        carPart =  soldPartsIterator.next();
    }
    return carPart;
}

The print statements are added so you can see what is going on when the code is running.
You should remove or comment them out when you verify the code works as expected!

Now our code has the ability to iterate through both lists in our Warehouse class!

Happy coding!




No comments:

Post a Comment