vendredi 8 mai 2020

Create different decorated object in case of input

Assume that I used decorated design pattern for making a pizza. There are 3 type of ingredients that user can add his pizza. Mozarella, souce and vegetables. I prepared these classes and set the cost.
This is main code

public class PizzaFactory {
    public static void main(String[] args) {
        Pizza p = new TomatoSauce(new Mozarella(new PlainPizza())); 
        System.out.println(p.getIngredients());
    }
}


This is interface

public interface Pizza {
    public String getIngredients();
    public int getCost();
}


This is base pizza

public class PlainPizza implements Pizza{
    @Override
    public String getIngredients() {
        return "Pizza ";
    }
    @Override
    public int getCost() {
        return 5;
    }
}


This is decorator class

abstract class IngredientDecorator implements Pizza{
    protected Pizza tempPizza;

    public IngredientDecorator(Pizza newPizza) {
        this.tempPizza = newPizza;
    }
    public String getIngredients() {
        return tempPizza.getIngredients();
    }
    public int getCost() {
        return tempPizza.getCost();
    }
}


One of ingredient class is

public class Mozarella extends IngredientDecorator{
    public Mozarella(Pizza newPizza) {
        super(newPizza);
    }

    public String getIngredients() {
        return tempPizza.getIngredients() + " Mozarella";
    }

    public int getCost() {
        return tempPizza.getCost() + 1;
    }
}


Others are look like them.
Now, I want to take input from user to which ingradient they want. In order to input I will create pizza. They may want just plain pizza. But since, I create my pizza -> Pizza p = new TomatoSauce(new Mozarella(new PlainPizza())); like this. How can I create pizza dinamic? Do I have to check each condition with if-else or switch-case?

Aucun commentaire:

Enregistrer un commentaire