Friday, August 22, 2014

Programming Design Pattern - Iterator Pattern Applied - Best Practise

Hi there!

Today i'm gonna show the Iterator design pattern in action. The Iterator design pattern is a very useful programming design pattern whenever you need to iterate over structures without knowing how this structure is implemented.

I'm assuming here you already know the concepts and i'll be focusing on practise. The example i will provide is a nice way to show it how it could looks like. You can always come back here, take it, adapt it and use it in your applictions as you may need. So be sure you bookmark it or join the group here on the right side of this post subscribing it.

First of all, let's take a look at the UML diagram of it. After that we will take the analogy for our example.

The UML Diagram of the Iterator Pattern


Pay close attention, because once you understand that, everything will become clear and simple to understand. That's the reason I'm putting always the UML first. That way you'll get an eye for it with the time.





The example

In our example we will see, how we could iterate over a restaurant's menu, showing the food options to our clients.

The Iterable and Iterator

Because those interfaces are part of the java default library, we will not invent the wheel again. So we will make usage of it. You don't need to implement it. I've just inserted here in case you want to understand the details and ideas behind it.

import java.util.Iterator;
public interface Iterable < T > {
    Iterator < T > iterator();
}
public interface Iterator < E > {
    boolean hasNext();
    E next();
    void remove();
}

The Product

Well, the idea behind the iterator is to iterate over a structure without knowing the details about this implementation. We just want to iterate over it to get some information about this structure. For this reason we first need a product (in our case Food) and a structure (in our case the MenuIterator). Note: in the real world we would name it just Menu. But for this tutorial here, I've intentionally defined MenuIterator to facilitate the understanding.

public class Food {
    private String name;
    private String description;
    private boolean vegetarian;
    private double price;
    public Food(String name, String description, boolean vegetarian, double price) {
        super();
        this.name = name;
        this.description = description;
        this.vegetarian = vegetarian;
        this.price = price;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public boolean isVegetarian() {
        return vegetarian;
    }
    public void setVegetarian(boolean vegetarian) {
        this.vegetarian = vegetarian;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    @Override
    public String toString() {
        return getName()+", "+getPrice()+" R$\n  - "+getDescription();
    }
}
public class MenuIterator implements Iterator < Food > {
    private Food[] foodOptions;
    int position = 0;
    MenuIterator(Food[] foodOptions){this.foodOptions=foodOptions;}
    @Override
    public boolean hasNext() {
        if(position > = foodOptions.length || foodOptions[position]==null){
            return false;
        }return true;
    }
    @Override
    public Food next() {
        final Food food = foodOptions[position];
        position++;
        return food;
    }
    @Override
    public void remove() {/*NOP*/}
}

The Barmaid

Our Barmaid will use the iterator to navigate over the menu showing the food options to the client.

public class Barmaid {
    private Iterable < Food > menu;
    public Barmaid(Menu menu) {
        this.menu = menu;
    }
    public void showMenu(){
        final Iterator < Food > iterator = menu.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next().toString());
        }
    }
}

The Test

Finally, we've opened our restaurant and the barmaid is showing the menu's to the clients. :)

public class Client {
    public static void main(String[] args) {
        String name = "Roast beef";
        String description = "Delicious roast beef argentino";
        boolean vegetarian = false;
        double price = 12.99;
        final Food roastBeef = new Food(name,description,vegetarian, price);
        name = "Sopa tomate";
        description = "Deliciosa sopa de tomate com oregano e creme de leite";
        vegetarian = true;
        price = 8.50;
        final Food sopaTomate = new Food(name,description,vegetarian, price);
        Food[] foodOptions = new Food[]{roastBeef, sopaTomate };
        final Menu menu = new Menu(foodOptions);
        final Barmaid barmaid = new Barmaid(menu);
        barmaid.showMenu();
    }
}

That's all! Hope you like it!

😱👇 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘‡

Be sure to read, it will change your life!
Show your work by Austin Kleonhttps://amzn.to/34NVmwx

This book is a must read - it will put you in another level! (Expert)
Agile Software Development, Principles, Patterns, and Practiceshttps://amzn.to/30WQSm2

Write cleaner code and stand out!
Clean Code - A Handbook of Agile Software Craftsmanship: https://amzn.to/33RvaSv

This book is very practical, straightforward and to the point! Worth every penny!
Kotlin for Android App Development (Developer's Library): https://amzn.to/33VZ6gp

Needless to say, these are top right?
Apple AirPods Pro: https://amzn.to/2GOICxy

😱👆 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘†