In: Computer Science
Imagine you're working for a fast-food restaurant. get details returns name of the burger and getPrice return the price of the meal. Java
Using Decorator pattern make class BurgerToppings:
-Each topping is an extra $1 and the name provided in the constructor
-getTotalPrice: returns total price of burger + toppings
-getDetails: returns the burger name + name of topping with the word (extra)
Output expected:
Ordering BigMac + extra pickles+ extra cheese
Total price = 6.0
public interface Burger{ double C(); String getDetails(); }
public class BigMac implements Burger{ private String order; private double price ; public BigMac() { this.order= "Big Mac"; this.price = 4.00; } @Override public double getPrice() { return price; } @Override public String getorder() { return name; } }
JAVA CODE: BurgerTester.java
NOTE: You can put each of the classes and interface in separate java files and then make all of them public, i have used only one java file for simplicity.
package project1;
interface Burger{
public double getPrice();
public String getDetails();
}
class BigMac implements Burger{
private String order;
private double price;
public BigMac() {
this.order="Big Mac";
this.price=4.00;
}
@Override
public double getPrice() {
return price;
}
@Override
public String getDetails() {
return order;
}
}
abstract class BurgerDecorator implements Burger{
protected Burger burger;
public BurgerDecorator(Burger burger) {
this.burger=burger;
}
@Override
public String getDetails() {
return burger.getDetails();
}
@Override
public double getPrice() {
return burger.getPrice();
}
}
class BurgerToppings extends BurgerDecorator{
private String toppings[];
public BurgerToppings(Burger burger, String
toppings[]) {
super(burger);
this.toppings=toppings;
}
@Override
public double getPrice() {
return burger.getPrice() +
toppings.length;
}
@Override
public String getDetails() {
StringBuilder sb=new
StringBuilder(burger.getDetails());
for(int
i=0;i<toppings.length;i++) {
sb.append(" +
extra "+toppings[i]);
}
return sb.toString();
}
}
public class BurgerTester {
public static void main(String[] args) {
BurgerToppings bt=new
BurgerToppings(new BigMac(),new String[]
{"pickles","cheese"});
System.out.println("Ordering
"+bt.getDetails());
System.out.println("Total price =
"+bt.getPrice());
}
}
Output: