I started learning the decorator pattern and it is the first time that i am faced with this kind of problem.
What bothers me is this line:
Drink drinkObject = new ChocolateDecorator(new SoyDecorator(new Espresso()));
Let's say i make a simple interface for the user to select the ingredients. How can i declare the object at runtime based on user input only?
Example: the user selects two "Soy" then the object should be:
Drink drinkObject = new SoyDecorator(new SoyDecorator(new Espresso()));
public class main {
public static void main(String[] args) {
Drink drinkObject = new ChocolateDecorator(new SoyDecorator(new Espresso()));
System.out.println("Order: "+ drinkObject.nameDescription());
System.out.println("Total Price: " + drinkObject.price());
}
}
abstract class Drink{
public abstract String nameDescription();
public abstract double price();
}
class Espresso extends Drink {
public String nameDescription() {
return "Expresso" + " with:";
}
public double price() {
return 1;
}
}
abstract class DrinkDecorator extends Drink {
protected Drink drink;
public DrinkDecorator(Drink drinkObject) {
this.drink = drinkObject;
}
public abstract String nameDescription();
public abstract double price();
}
class ChocolateDecorator extends DrinkDecorator{
public ChocolateDecorator(Drink drinkObject) {
super(drinkObject);
}
public String nameDescription() {
return this.drink.nameDescription()+ " Chocolate;";
}
public double price() {
return this.drink.price() + 0.25;
}
}
class SoyDecorator extends DrinkDecorator{
public SoyDecorator(Drink drinkObject) {
super(drinkObject);
}
public String nameDescription() {
return this.drink.nameDescription()+ " Soy;";
}
public double price() {
return this.drink.price() + 0.15;
}
}
Aucun commentaire:
Enregistrer un commentaire