Follow treslines by email clicking Here!

Wednesday, August 20, 2014

Programming Design Pattern - Composite Pattern Applied - Best Practise

Hi there!

Today i'm gonna show the Composite design pattern in action. The Composite design pattern is a very useful programming design pattern while dealing with trees, folders and structures.

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 Composite 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 implement a menu structure for a restaurant. How could we do it? In this example we will see it.

The Menu Component

That's the base class for all menu itens (topics) and sub-itens (menu itself)

public abstract class MenuComponent {
    // MAKE INTERFACE FROM FOOD
    public String getName(){throw new UnsupportedOperationException();}
    public void setName(String name){throw new UnsupportedOperationException();}
    public String getDescription(){throw new UnsupportedOperationException();}
    public void setDescription(String description){throw new UnsupportedOperationException();}
    public boolean isVegetarian(){throw new UnsupportedOperationException();}
    public void setVegetarian(boolean vegetarian){throw new UnsupportedOperationException();}
    public double getPrice(){throw new UnsupportedOperationException();}
    public void setPrice(double price){throw new UnsupportedOperationException();}
    public void showMenu(){throw new UnsupportedOperationException();}
    // COMPOSITE METHODS
    public void add(MenuComponent component){throw new UnsupportedOperationException();}
    public void remove(MenuComponent component){throw new UnsupportedOperationException();}
    public MenuComponent getChild(int index){throw new UnsupportedOperationException();}
}

The Menu itens

Well, let´s implement the base item we wanna offer in our restaurant. (Food)

public class Food extends MenuComponent{
    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;}
    public void showMenu() {System.out.println(toString());}
    @Override
    public String toString() {
        return getName()+", R$"+getPrice()+" - vegetário: "+isVegetarian()+"\n  - "+getDescription();
    }
}

The Menu ifself

Well, if we want to present the restaurant's specialties, we must define the menu itself. This happens here.

public class Menu extends MenuComponent {
    private List < MenuComponent > tree =  new ArrayList < MenuComponent > ( );
    private String name, description;
    public Menu(String name, String description) {
        this.name = name; this.description = description;
    }
    public String getName() {return name;}
    public String getDescription() {return description;}
    public void showMenu() {
        System.out.println(getName());
        System.out.println(getDescription());
        System.out.println("--------------------");
        final Iterator iterator = tree.iterator();
        while(iterator.hasNext()){
            iterator.next().showMenu();
        }
    }
    public void add(MenuComponent component) {tree.add(component);}
    public void remove(MenuComponent component) {tree.remove(component);}
    public MenuComponent getChild(int index) {return tree.get(index);}
}

The Barmaid

Also need someone that that receives the orders from the customers. So let´s define it.

public class Barmaid {
    private MenuComponent menus;
    public Barmaid(MenuComponent menus) {
        this.menus = menus;
    }
    public void showMenus(){
        menus.showMenu();
    }
}

The Test

Finally, let´s test our brand new restaurant´s menu and see how it works in practise.

public class Client {
    public static void main(String[] args) {
        MenuComponent meatMenu = new Menu("Carnes", "Cardapio de carnes nobres");
        MenuComponent soupMenu = new Menu("Sopas", "Cardapio de sopas vegetárianas");
        MenuComponent coffeeMenu = new Menu("Cafes", "Cardapio de café");
        MenuComponent allMenusTogether = new Menu("Todos cardapios", "Todas ofertas do nosso restaurante");
        // ADD MENU'S TO THE GENERAL MENU
        allMenusTogether.add(meatMenu);
        allMenusTogether.add(soupMenu);
        allMenusTogether.add(coffeeMenu);
        // ADD FOOD TO THE MEAT MENU
        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);
        meatMenu.add(roastBeef);
        // ADD FOOD TO THE SOUP MENU
        name = "Sopa tomate";
        description = "Deliciosa sopa de tomate com oregano e creme de leite";
        vegetarian = true;
        price = 8.50;
        final Food tomatoSoup = new Food(name,description,vegetarian, price);
        soupMenu.add(tomatoSoup);
        // ORDER MENU'S FROM BARMAID (BARMAID SHOWS THE AVAILABLE MENU'S)
        final Barmaid barmaid = new Barmaid(allMenusTogether);
        barmaid.showMenus();
    }
}

That's all. Hope you like it!

No comments:

Post a Comment