Skip to content
Advertisement

Method to display particular types of pizza from a list in Java

I have a simple pizza program in Java, made using the Factory Pattern. Basically, when a factory is given as a parameter, it creates a particular pizza, which is then added to the list of pizzas of the PizzaShop.

I would like to create a method that displays how many particular pizzas I have. For instance, when the method is called, I would like it to display something like “We have 5 PizzaChicago and 3 PizzaNewYork”. I am not sure how to do that.

This is my code.

public interface Pizza {
    String name();
}

public class PizzaChicago implements Pizza{
    public Integer price;
    public PizzaChicago(Integer price){
        this.price = price;
    }

    @Override
    public String name() {
        return this.getClass().getSimpleName();
    }
}

public class PizzaNewYork implements Pizza{
    public Integer price;
    public PizzaNewYork(Integer price){
        this.price = price;
    }
    @Override
    public String name() {
        return this.getClass().getSimpleName();
    }
}


public interface PizzaFactory {
   public Pizza createPizza(Integer price);
}

public class PizzaNewYorkFactory implements PizzaFactory{
    @Override
    public Pizza createPizza(Integer price) {
        return new PizzaNewYork(6);
    }
}

public class PizzaChicagoFactory implements PizzaFactory{
    @Override
    public Pizza createPizza(Integer price) {
        return new PizzaChicago(8);
    }
}

import java.util.ArrayList;
import java.util.List;

public class PizzaShop {
    List<Pizza> pizzaList = new ArrayList<>();
    public void createPizza(PizzaFactory factory, Integer price){
        Pizza pizza = factory.createPizza(price);
       System.out.println(pizza.name() + " " + "was created");
        pizzaList.add(pizza);
    }

}
`

Advertisement

Answer

What you have to do is iterate the list and check what is the type of every object.

int countPizzaNewYork = 0, countPizzaChicago = 0; 
for(Pizza p: pizzaList){
    if(p instanceOf PizzaNewYork)
    {
     countPizzaNewYork++;
    }
    else
    {
     countPizzaChicago++;
    }

 }
System.out.println("We have "+ countPizzaChicago+" PizzaChicago and "+countPizzaNewYork+" PizzaNewYork");
Advertisement