dimanche 23 juillet 2017

Decorator Pattern from Head First Book wrongfully used?

Currently I am reading "Head First Design Patterns". As you may look on pages 24 and 25 of the PDF here, I have doubt in given example.

Why don't we make something like:

public abstract class Beverage {

String description = "Unknown Beverage";
Double cost;
ArrayList<Topping> toppings;  // allows duplicates


public void addTopping(Topping topping){
toppings.add(topping);
cost+=topping.getCost();
}
getter/setter of description
getter/setter of cost
}



Public class Topping{
 String description;
 double cost;

    getter/setter of description
    getter/setter of cost

}

Then answering questions on page 25:

  • Price changes for condiments will force us to alter existing code

    no they won't we can manipulate cost of the topping by setter.

  • New condiments will force us to add new methods and alter the cost method in the superclass

    no, the method is the same.

  • What if a customer wants a double mocha?

    not a problem

Here we can also add Builder pattern.

Why should you use the decorator pattern in this scenario? Is my solution not enough?

Aucun commentaire:

Enregistrer un commentaire