0

I'm working on a basic Pizza program.The program add toppings into pizza by using Decorator Pattern Design.

public static void main(String[] args) {
    Pizza pizza = new PizzaBakery();
    //lets put Onion,Pepper and Salami into pizza:
    pizza = new Salami(new Pepper(new Onion(pizza)));}

My code works well and manage to create pizza&put its toppings. The problem is that, I'll take pizza&Toppings orders from an input file.

Input file example:

AddTopping 7 HotPepper Soudjouk Salami (7 is the ID of the pizza)

AddTopping 1 HotPepper Onion

.....

and adding toppings into pizza must be nested(like new Salami(new Pepper(new Onion(pizza))) ) .Is there any different way/method to use instead of writing many if-else statements ?

Edit: There will be 4 different toppings in file and a pizza can include 3 toppings at most.

Eren
  • 3
  • 4

2 Answers2

0

Why are you thinking you will have a lot of ifs? I am assuming you mean you will parse the order, then have to construct a string of calls based on what you find there. The problem I see here is that Decorator requires a compile time calling construction. Furthermore, Decorator is mostly meant for cases where you are adding something orthogonal, that the host class need not know about. What you are doing would probably fit Chain of Responsibility better.

The nice thing about Chain of Responsibility is:

  • you can construct the chain at runtime, then invoke the first item and it would cascade down through the sequence of handlers
  • also, you could enforce ordering if need be, for instance, if I order onions and mushrooms, probably want the onions put on first

Or, you could model the order parsing as Interpreter and make the construction process into a Visitor Pattern. (Common way of pairing the construction of an AST and then its evaluation.)

Rob
  • 11,446
  • 7
  • 39
  • 57
-1

Your code looks weird for me. First, you said:

Pizza pizza = new PizzaBakery();

Then you did:

pizza = new Salami(new Pepper(new Onion(pizza)));

That means "pizza" now is an object of "Salami". According to your description, I will do something like this:

  1. Add a method in Pizza class:

    public class Pizza {
        // constructor
        public Pizza (...) {
        // ...
        }
    
        // function to add toppings
        public void addToppings (Salami s, Pepper p, Onion o) {
        // ...
        }
    }
    
  2. Now re-write your main function like this:

    public static void main (String[] args) {
        Pizza pizza = new Pizza();
        Salami s1 = new Salami(...);
        Pepper p1 = new Pepper(...);
        Onion  o1 = new  Onion(...);
        pizza.addToppings(s1, p1, o1);
    }
    
Heran
  • 19
  • 1
  • 1
  • 8